如何使用Linq获得此分组结果 [英] how to get this grouped result using Linq

查看:141
本文介绍了如何使用Linq获得此分组结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下的Foo课.

public class Foo
{
    public string Name { get; set; }
    public string Value { get; set; }   
}

我有一个此类的集合,比如说List,有时我在集合中有如下数据.

I have a collection of this class let's say List and sometimes I have data as follows in collection.


 Name           Value   
Jimmy           hello   
Jimmy           World   
Peter           how  
Peter           are you?   
Suzanne         I am fine

我想将与以下名称相同的名称的值字段组合在一起

I want to combine the value field for same Names as folows


Name            Value  
Jimmy           hello World  
Peter           how are you?  
Suzanne         I am fine  

无论如何,这可以使用Linq完成吗?

Is there anyway this could be accomplished using Linq?

推荐答案

您可以按以下方式使用Linq GroupBy:

You can use the Linq GroupBy as follows:

fooCollection.GroupBy(foo => foo.Name)

    // create a new "Foo" object based on each grouping
    .Select(g => new Foo() { 

        // "Name" becomes the group key (ie, "Jimmy", "Peter", etc)
        Name = g.Key, 

        // "Value" becomes the Value for all Foo in this group, concatenated
        Value = string.Join(" ", g.Select(item => item.Value).ToArray()) 
    })
    .ToArray();

这篇关于如何使用Linq获得此分组结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆