使用C#将多个值分组为一个序列

时间:2010-10-20 20:48:51

标签: c# lambda

我有以下列表:

UserName  LanguageSpoken
-------------------------
Bob       English
Bob       French
Alan      Italian
Alan      Spanish
Alan      German

我希望有另一个列表:

Bob       English/French
Alan      Italian/Spanish/German

如何在C#中使用lambda表达式。

由于

4 个答案:

答案 0 :(得分:2)

我的方法是使用正则表达式来解析数据,然后使用linq对其进行分组。你能告诉我们你到目前为止所尝试的内容吗?

答案 1 :(得分:2)

以下是您可以使用的实现。

class UserLanguage
{
    public string UserName { get; set; }

    public string Language { get; set; }
}

static class EnumerableExtensions
{
    public static string Concatenate(this IEnumerable<string> source, string delimiter)
    {
        using (var enumerator = source.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                StringBuilder builder = new StringBuilder(enumerator.Current);
                while (enumerator.MoveNext())
                {
                    builder.Append(delimiter).Append(enumerator.Current);
                }
                return builder.ToString();
            }
            else
            {
                return null;
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        // assuming that you already have data stored in a structure similar to this
        var rawData = new List<UserLanguage>()
        {
            new UserLanguage { UserName = "Bob", Language = "English" },
            new UserLanguage { UserName = "Bob", Language = "French" },
            new UserLanguage { UserName = "Alan", Language = "Italian" },
            new UserLanguage { UserName = "Alan", Language = "Spanish" },
            new UserLanguage { UserName = "Alan", Language = "German" },
        };

        // group these objects together by UserName
        var groupedData = rawData.GroupBy(userLanguage => userLanguage.UserName);

        foreach (var grouping in groupedData)
        {
            Console.WriteLine(grouping.Key + "\t" + grouping.Select(userLanguage => userLanguage.Language).Concatenate("/"));
        }
    }
}

答案 2 :(得分:2)

     class Person
        {
         string UserName {get;set;}
         string LanguageSpoken {get; set;}    
        }

    List<Person> table = new List<Person>()
    { new Person(){UserName="Bob"; LanguageSpoken = "English"}
    /* next persons*/
    };

var userNameGroups = from n in table
        group n by n.UserName into g
        select new { keyUserName = g.Key, LanguageSpoken = g };

    foreach (var g in numberGroups)
    {
        Console.Write(g.keyUserName.ToString());
        foreach (var n in g.LanguageSpoken)
        {
            Console.WriteLine(n.ToString());
        }
    }

答案 3 :(得分:1)

如果您的列表类似于:

class Person
{
    public string Name { get; set; }
    public string Language { get; set; }
}

List<Person> myList = /* Initialization */

然后LINQ GroupBy应该这样做:

myList.GroupBy(a => a.Name);

希望这有帮助。