-1

我有这个:

class MyContact
{
    public string firstname { get; set; }
    public string lastname { get; set; }
}

MyContact c1 = new MyContact() { firstname = "Filipe", lastname = "Silva" };
MyContact c2 = new MyContact() { firstname = "Filipe", lastname = "Oliveira" };
MyContact c3 = new MyContact() { firstname = "Maria", lastname = "Santos" };
MyContact c4 = new MyContact() { firstname = "Jose", lastname = "Ricardo" };
MyContact c5 = new MyContact() { firstname = "Joao", lastname = "Roberto" };
MyContact c6 = new MyContact() { firstname = "Joao", lastname = "Augusto" };
MyContact c7 = new MyContact() { firstname = "Joao", lastname = "Mario" };

var cList = new List<MyContact>();
cList.AddRange(new MyContact[] { c1, c2, c3, c4, c5, c6, c7 });

我需要 GroupBy firstname 并连接所有姓氏。

这是我的预期结果:

Filipe - Silva|Oliveira
Maria - Santos
Jose - Ricardo
Joao - Roberto|Augusto|Mario
4

2 回答 2

2

您可以使用此代码创建一个列表:

var result = new List<string>();

foreach (var group in cList.GroupBy(x => x.firstname))
{
    var lastnames = String.Join("|" , group.Select(x => x.lastname));
    result.Add(String.Format("{0} - {1}", group.Key, lastnames));
}
于 2013-08-13T13:37:32.990 回答
0

Dictionary 的另一个选项:

var concat = new Dictionary<string, string>();
foreach (MyContact c in cList)
{
    if (concat.ContainsKey(c.firstname))
       concat[c.firstname] += "|" + c.lastname;
    else
       concat.Add(c.firstname,c.lastname);
}

如果您想将名字和姓氏分开,这可能会很有用

于 2013-08-13T13:41:16.003 回答