选择多个C#的组和总和?

The*_*Dev 4 c# linq grouping concatenation

我有一个传入的数组,每行有一个计数和一个字符串,表示一个或多个键由下划线分割.

对于每个键我想分组并总和总和,如果键出现在一行中总共5,每个项目由下划线分开,其总数增加5.

我只是想知道如何在linq中表示...

 class Owl
    {
        public int SpeciesCount { get; set; }
        public string BandIdentifier { get; set; }
    }

public class GoOwl
{
    public GoOwl(Owl[] owls)
    {
       //just making a list of test data to illustrate what would be coming in on the array
        var owlList = new List<Owl>();
        owlList.Add(new Owl { SpeciesCount = 2, BandIdentifier = "OWL1" });
        owlList.Add(new Owl { SpeciesCount = 1, BandIdentifier = "OWL1_OWL2_OWL3" });
        owlList.Add(new Owl { SpeciesCount = 2, BandIdentifier = "OWL3" });
        owlList.Add(new Owl { SpeciesCount = 5, BandIdentifier = "OWL2_OWL3" });

        //i'd ideally like to have something like a row for each band identifier split on underscore plus a total species count..
        //where you'd sum the species count for each underscored item and group


    }
}
Run Code Online (Sandbox Code Playgroud)

以下是单个Owl对象的所需输出

["OWL1", 3]
["OWL2", 6]
["OWL3", 8]
Run Code Online (Sandbox Code Playgroud)

我还没有得到SelectMany ..

干杯

Ben*_*ich 8

在流利的sytnax:

//For each 'owlItem' in the owlList, select an anonymous objects for each key in the BandIdentifier string, keeping track of the associated SpeciesCount
//Since each call to Split('_').Select(...) produces an IEnumerable of those anonymous objects, use SelectMany to flatten the IEnumerable to IEnumerables 
owlList.SelectMany(owlItem => owlItem.BandIdentifier.Split('_')
                .Select(key => new { OwlKey = key, owlItem.SpeciesCount }))
            //Group together those anonymous objects if they share the same key
            .GroupBy(info => info.OwlKey)
            //For each of the groups, sum together all the associated SpeciesCounts
            .Select(group => new { group.Key, SpeciesCount = group.Sum(info => info.SpeciesCount) })'
Run Code Online (Sandbox Code Playgroud)