4

行ごとのカウントと、アンダースコアで分割された 1 つ以上のキーを表す文字列を含む着信配列があります。

キーごとにグループ化して合計を合計したいのですが、キーが合計 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


    }
}

以下は、単一の Owl オブジェクトとしての望ましい出力です。

["OWL1", 3]
["OWL2", 6]
["OWL3", 8]

私はまだSelectManyを完全に取得していません..

乾杯

4

3 に答える 3

8

流暢な構文で:

//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) })'
于 2013-05-07T14:23:10.470 に答える
3

これが欲しいようです:

var results =
    owlList.SelectMany(owl => owl.BandIdentifier.Split('_'), 
                       (owl, band) => new { owl, band })
           .GroupBy(x => x.band)
           .Select(group => new Owl 
                   {
                       BandIdentifier = group.Key
                       SpeciesCount = group.Sum(g => g.SpeciesCount)
                   });

またはクエリ構文で:

var results =
    from owl in owlList
    from band in owl.BandIdentifier.Split('_')
    group owl by band into group
    select new Owl {
        BandIdentifier = group.Key
        SpeciesCount = group.Sum(g => g.SpeciesCount)
    };
于 2013-05-07T14:18:31.273 に答える