如何从对象列表中获取特定的对象集

时间:2014-07-01 22:26:40

标签: c# linq

List<objects> MyObjects = GetobjectsfromList(otherlist);

我正在使用的MyObjects列表有多个属性

String name;

String locationInfo;

String otherObjectName;

DateTime date1;

DateTime date2;

(等)

MyObjects中包含的内容如下:

Obj1 (name1, location1, otherobjectname1, date1, date2)

Obj2 (name2, location2, otherobjectname1, date4, date7)

Obj3 (name3, location3, otherobjectname1, date6, date9)

Obj4 (name4, location6, otherobjectname2, date1, date2)

Obj5 (name5, location7, otherobjectname2, date1, date2)

(总共大约2600条记录,属性使每条记录都是唯一的)

基本上所有ObJ对象都至少有一个属性使它们对集合是唯一的。因此,使用任何groupby,或distinct,或者我试过的任何其他linq .where子句总是让我回到整个集合,因为每条记录都是真正独特的。

我需要的是从这个对象的整个集合中获取每个对象中的一个,以获得对象上的不同属性...即otherobjectname。看一下有3条记录,然后另外2条记录(我从这些其他对象名做了一个哈希集,只有975条记录)。

我需要从这个集合中获得的只是一个新的MyObjects集合,其中我只为每个其他对象名称都有一个,我不关心它是哪个记录。

所以返回包含这些内容的新列表:

Obj1 (name1, location1, otherobjectname1, date1, date2) (I do not care which of the 3)

Obj4 (name4, location6, otherobjectname2, date1, date2) (I do not care which of the 2)

等等集合中的每个唯一的其他对象名称

该对象的其中一个属性只有一个唯一记录 有办法做到这一点吗?抱歉,我无法真正发布示例代码,因为安全规则,我试图在没有使用任何特定内容的情况下尽我所能写出来。

2 个答案:

答案 0 :(得分:0)

您可以使用DistinctBy方法(它不是标准的Linq方法,但您可以在MoreLinqLinq.Extras中找到它的实现。)

var distinct = MyObjects.DistinctBy(x => w.OtherObjectName);

或者如果您愿意,您可以创建一个自定义相等比较器,仅比较OtherObjectName属性,并将其传递给Distinct

class MyObjectComparerByOtherObjectName : IEqualityComparer<MyObject>
{
    public bool Equals(MyObject x, MyObject y)
    {
        return x.OtherObjectName == y.OtherObjectName;
    }

    public bool GetHashCode(MyObject x)
    {
        return x.OtherObjectName != null ? x.OtherObjectName.GetHashCode() : 0;
    }
}

...

var distinct = MyObjects.Distinct(new MyObjectComparerByOtherObjectName());

答案 1 :(得分:0)

您可以按otherObjectName进行分组,从组中选择第一个,如下所示:

static void Main(string[] args)
{
    List<MyObject> objects = new List<MyObject> {
        new MyObject { name = "name1", locationInfo = "location1", otherObjectName = "otherobjectname1" },
        new MyObject { name = "name2", locationInfo = "location2", otherObjectName = "otherobjectname1" },
        new MyObject { name = "name3", locationInfo = "location3", otherObjectName = "otherobjectname1" },
        new MyObject { name = "name4", locationInfo = "location6", otherObjectName = "otherobjectname2" },
        new MyObject { name = "name5", locationInfo = "location7", otherObjectName = "otherobjectname2" },
    };

    var query = objects.GroupBy(o => o.otherObjectName)
        .Select(g => g.First());

    foreach(var o in query)
        Console.WriteLine("{0} {1}", o.name,  o.otherObjectName);
}

返回:

name1 otherobjectname1
name4 otherobjectname2