2016-07-04 54 views
1

我有2個包含字符和字符數的IEnumerable集合(即s1 {Key ='a'Count ='5'}和s2 {Key =「A」數=「4」})如何使用Linq從匿名IEnumerable集合中選擇項目

我想要做的LINQ查詢以下內容:

,如果該項目是在兩個集合,我只想從集合具有較高計數的項目,即從s1計數= 5

如果項目只在一個集合中,那麼我們使用該項目(不能使用Distinct,因爲它說IEnumerable匿名不包含Distinct)

如果項目在兩個集合中,但它們的計數相等,則使用哪一個並不重要。

不知道這部分出來,我敢肯定,一旦我看到的解決辦法,我會想我的頭撞到牆上......

+0

請發佈您嘗試過的示例代碼。 –

+0

items.GroupBy(a => a.Key).Select(gr => new {Key = a.Key,Count = gr.Max(aa => aa.Count))}) – omikad

回答

3

您可以按Key並選擇最大Count

var collection1 = "testtt".GroupBy(c => c).Select(g => new { Key = g.Key, Count = g.Count() }); 
var collection2 = "teessst".GroupBy(c => c).Select(g => new { Key = g.Key, Count = g.Count() }); 

var result = collection1.Concat(collection2) 
    .GroupBy(item => item.Key, item => item.Count) 
    .Select(g => new { Key = g.Key, Count = g.Max() }); 
6

使用Linq擴展功能,你可以做到這一點。

Dictionary<char,int> dic1 = ...; 
Dictionary<char,int> dic2 = ...; 

var result = dic1.Concat(dic2) 
    .GroupBy(g=>g.Key) 
    .ToDictionary(x=>x.Key, x=>x.Max(m=>m.Value)) ; 

在情況下,如果你有一個包含key, countfields/properties它的基本型兩個集合,然後嘗試用這個。

var result = list1.Concat(list2) 
    .GroupBy(g=>g.Key) 
    .Select(x=>new     // Create an object instead if you have one. 
    { 
     x.Key, 
     x=>x.Max(m=>m.Count) 
    }; 

入住這Demo

+1

爲什麼要使用字典? OP似乎不是。 – Enigmativity

2

我認爲這是相當直截了當:

var s1 = new [] { new { Key = 'a', Count = 5 }, new { Key = 'b', Count = 2 } }; 
var s2 = new [] { new { Key = 'a', Count = 4 }, new { Key = 'c', Count = 7 } }; 

var result = 
    s1 
     .Concat(s2) 
     .OrderByDescending(x => x.Count) 
     .GroupBy(x => x.Key) 
     .SelectMany(x => x.Take(1)); 

它給我:

result

+0

如果您對我的更新滿意,您可以刪除您的投票嗎? –