2014-07-01 53 views
1
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子句我尝试过总是让我回到整个集合,因为每个记录都是独一无二的。

我需要的只是从这个对象的整个集合中获得每个对象的一个​​,以获得对象上的不同属性...即其他对象的名称。看看有一条记录是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) 

等了集合中的每个独特的otherobjectname

为对象 上的一个属性只是一个唯一的记录是有一些如何做到这一点?对不起,我不能真正发布示例代码,我试图尽我所能写出最好的,因为没有使用任何特定的安全规则。

回答

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()); 
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 
相关问题