0

如何在不使用匿名类型的情况下返回每个成员的类型为 Member 的 groupedMembers 及其所有现有值和更改后的 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)
4

1 回答 1

0

If Name is what makes GenericDataRow unique then you need to implement the IEquatable<GenericDataRow> as well as overriding GetHashCode and Equals(object). Example below.

    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);
        }
    }

With the following 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()) };
于 2013-03-27T13:48:39.190 回答