2014-07-01 50 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 
相關問題