如何拆分List但保留groupBy

时间:2013-11-15 22:30:27

标签: c# linq split

我有以下形式的键/值对列表:

[{John:6},{Alex:100},{Peter:4},{Peter,John:5},{Alex,Kati:1}]

我想知道是否有一个简单的linq表达式可以用来将列表翻译成

[{John:11},{Alex:101},{Peter:9},{Kati:1}]

即用逗号分割字符串并调整计数。

上面的列表来自以下LINQ

var list = people.Where(a => !string.IsNullOrWhiteSpace(a.Name))
.GroupBy(a => a.Name.Trim()).Select(a => new User { Name = a.Key, Items= a.Count() });

4 个答案:

答案 0 :(得分:0)

使用

var list = new[]
{
    new KeyValuePair<string, int>("John", 6),
    new KeyValuePair<string, int>("Alex", 100),
    new KeyValuePair<string, int>("Peter", 4),
    new KeyValuePair<string, int>("Peter,John", 5),
    new KeyValuePair<string, int>("Alex,Kati", 1)
};

这个分组

var modifiedList = list.SelectMany(p => p.Key.Split(',').Select(n => new {Name = n, Number = p.Value}))
    .GroupBy(p => p.Name).Select(g => new KeyValuePair<string, int>(g.Key, g.Sum(r => r.Number)));

为您提供输出

{[John, 11]}
{[Alex, 101]}
{[Peter, 9]}
{[Kati, 1]}

答案 1 :(得分:0)

试试这个:

var list = new List<KeyValuePair<string, int>>
        {
            new KeyValuePair<string,int>("John", 6),
            new KeyValuePair<string,int>("Alex", 100),
            new KeyValuePair<string,int>("Peter", 4),
            new KeyValuePair<string,int>("Peter,John", 5),
            new KeyValuePair<string,int>("Alex,Kati", 1)                
        };
var result = list.SelectMany(x => x.Key.Split(','),
                                    (x, y) => new KeyValuePair<string, int>(y, x.Value))
                 .GroupBy(x => x.Key)
                 .ToDictionary(key => key.Key, value => value.Sum(x => x.Value));                             

答案 2 :(得分:0)

Dictionary<string, int> result = keyVals
    .SelectMany(kv =>  kv.Key.Split(',').Select(name => new{ name, kv.Value }))
    .GroupBy(x => x.name)
    .ToDictionary(xg => xg.Key, xg => xg.Sum(x => x.Value));

结果:

{[John, 11]}     
{[Alex, 101]}   
{[Peter, 9]}    
{[Kati, 1]}  

Demo

答案 3 :(得分:0)

所以你有这样的课程

public class Person
{
    public string Name { get; set; }
}
public class User
{
    public string Name { get; set; }
    public int Items { get; set; }
}

如果我理解正确,你想要计算每个名字出现的次数

var people = new[]
{
    new Person { Name = "John" },
    new Person { Name = "John,Alex" },
    new Person { Name = "Alex" },
    new Person { Name  ="Peter,John" }
};

var list = people.SelectMany(p => p.Name.Split(','))
    .GroupBy(n => n)
    .Select(g => new User { Name = g.Key, Items = g.Count() });