返回具有原始实体而非匿名类型的分组集合

时间:2013-03-27 12:20:12

标签: c# linq

如何在不使用匿名类型的情况下返回其中每个成员为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)

1 个答案:

答案 0 :(得分:0)

如果NameGenericDataRow唯一的,那么您需要实施IEquatable<GenericDataRow>以及覆盖GetHashCodeEquals(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()) };