如何在不使用匿名类型的情况下返回其中每个成员为Member类型的groupsMembers及其所有现有值和更改后的Name属性?
我不想使用.Select()方法复制/粘贴匿名类型中的所有原始成员值...
var groupedMembers = from r in dataRows
join m in members on r.Name equals m.Name
group r by r.Name into g
select new { Name = String.Format("{0} ({1})", g.Key, g.Count()) };
var dataRows = new List<GenericDataRow> {
new GenericDataRow { Name = "E1" },
new GenericDataRow { Name = "E1" },
new GenericDataRow { Name = "E1" },
new GenericDataRow { Name = "E1" },
new GenericDataRow { Name = "E2" },
new GenericDataRow { Name = "E2" },
new GenericDataRow { Name = "E2" }
};
var members = new List<OtlClientMember> {
new Member { Name = "E1" },
new Member { Name = "E2" },
new Member { Name = "E3" },
new Member { Name = "E4" },
};
输出
E1 (4)
E2 (3)
答案 0 :(得分:0)
如果Name
是GenericDataRow
唯一的,那么您需要实施IEquatable<GenericDataRow>
以及覆盖GetHashCode
和Equals(object)
。示例如下。
private class GenericDataRow : IEquatable<GenericDataRow>
{
public string Name { get; set; }
public bool Equals(GenericDataRow other)
{
return Name.Equals(other.Name);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
public override bool Equals(object obj)
{
return Equals(obj as GenericDataRow);
}
}
使用以下Linq:
var groupedMembers = from r in dataRows
join m in members on r.Name equals m.Name
group r by r into g
select new { Name = String.Format("{0} ({1})", g.Key.Name, g.Count()) };