我有一个传入数组,每行有一个计数,一个字符串代表一个或多个由下划线分隔的键。
对于我想对每个键进行分组并求和的总数,如果该键出现在一行中且总数为 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..
干杯
最佳答案
流利的语法:
//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) })'
关于c# - 使用选择多个 C# 进行分组和求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16421233/