假设这是我的会员类
class Member
{
public string CategoryId { get; set; }
public string MemberName { get; set; }
public int Distance { get; set; }
}
而且,这是列表。
var list = new List<Member>();
list.Add(new { CategoryId = "01", MemberName = "andy", Distance = 3 });
list.Add(new { CategoryId = "02", MemberName = "john", Distance = 5 });
list.Add(new { CategoryId = "01", MemberName = "mathew", Distance = 7 });
list.Add(new { CategoryId = "03", MemberName = "bakara", Distance = 2 });
任何人都可以建议逻辑/ linq查询以使List具有不同的/唯一的categoryID,其中各个MemberNames用逗号分隔
输出应为:
list.Add(new { CategoryId = "01", MemberName="andy,mathew"});
list.Add(new { CategoryId = "02", MemberName="john"});
list.Add(new { CategoryId = "03", MemberName="bakara"});
答案 0 :(得分:2)
您需要按CategoryId
进行分组,然后加入每个组的MemberName
值,如下所示:
var result =
list.GroupBy(member => member.CategoryId)
.Select(group => new //Do you want an anonymous type or a Member object?
{
CategoryId = group.Key,
MemberName = string.Join(",", group.Select(member => member.MemberName))
})
.ToList();