我有这个:
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 });
我需要按名字分组并连接所有姓氏。
这是我的预期结果:
Filipe - Silva|Oliveira
Maria - Santos
Jose - Ricardo
Joao - Roberto|Augusto|Mario
答案 0 :(得分: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));
}
答案 1 :(得分:0)
带字典的另一个选项:
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);
}
如果您想要保留名字和姓氏
,这可能会很有用