c# - 使用选择多个 C# 进行分组和求和?

标签 c# linq concatenation grouping

我有一个传入数组,每行有一个计数,一个字符串代表一个或多个由下划线分隔的键。

对于我想对每个键进行分组并求和的总数,如果该键出现在一行中且总数为 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/

相关文章:

c# - 使用 Sendgrid 在 Azure 上发送简单的电子邮件

c# - UPDATE 语句中的语法错误 OleDb 异常

c# - "Invalid Cast"在 Linq 中

c# - LINQ to Objects 缓慢。现在我完全糊涂了

python - 使用 pandas 创建多索引

c# - asp.net c# 以编程方式更改编辑按钮样式

c# - 检测到不适用于集成托管管道模式的 ASP.NET 设置。(该项目甚至不在本地运行)

list - Scala 中列表串联(:::)的复杂性?

c# - 计算数组数组中等于指定值的元素

postgresql - 在 PostgreSQL 中连接属性