群和总结选择许多C#?
问题描述:
我有一个传入的数组,每行的计数和一个字符串表示一个或多个按键的下划线分隔。群和总结选择许多C#?
每个我想组和求和总其中如果键出现在一行中,共有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
}
}
以下将所需的输出为单猫头鹰对象
["OWL1", 3]
["OWL2", 6]
["OWL3", 8]
我仍然不是很让小号electMany ..
干杯
答
用流利的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) })'
答
好像你想要这个:
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)
};
答
var owlResults = owlList
//Use SelectMany to split and select all species
//and have a select to get the count along with the species
.SelectMany(O => O.BandIdentifier.Split('_')
.Select(owl => new { Species = owl, Count = O.SpeciesCount }))
//Here you can group and get the sum
.GroupBy(O => O.Species)
.Select(owl => new { Species = owl.Key, Count = owl.Sum(o => o.Count) });
谢谢Ben!你介意在这种情况下解释selectmany的工作原理吗?我知道它会展平嵌套的集合,所以在这个例子中,它是在执行以下的操作:[OWL1 2] [OWL1 1] [OWL2 1] [OWL3 1] [OWL3 2] [OWL2 5] [OWL3 5]那么按组上的密钥然后你可以总结? – TheLearningDev 2013-05-07 15:25:19
每次调用.Split('_')。选择(...)将生成一个IEnumerable。由于我们正在为owlList变量的每个元素调用该方法链,所以我们有一个IEnumerable的IEnumerables,可以使用SelectMany进行展平。换句话说,由于列表中的每个元素都会生成一个OwlKey/SpeciesCount组合列表,所以在开始分组和求和之前,我们需要将列表生成的列表展平。 – 2013-05-07 15:33:15
感谢本和谢谢你的解释我很感激你花时间! :) – TheLearningDev 2013-05-07 22:21:21