MattE
MattE

Reputation: 1114

How to use Linq to select items from a anonymous IEnumerable collection

I have got 2 IEnumerable Collections that contain a character and the count of the character(ie s1{Key = 'a' Count='5'} and s2{Key='a' Count = '4'})

I want to do the following with a Linq query:

if the item is in both collections, I only want the item from collection with the higher count, ie Count=5 from s1

if the item only is in one collection, then we use that item(can't use Distinct because it says IEnumerable Anonymous doesn't contain Distinct)

if the items are in both collections but their counts are equal, it doesn't matter which one we use.

Cannot figure this part out, I am pretty sure once I see the solution I am going to want to bang my head into a wall...

Upvotes: 1

Views: 419

Answers (3)

Hari Prasad
Hari Prasad

Reputation: 16956

Using Linq extension functions you could do this.

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

In case if you have two collections of which the underlying type containing key, count fields/properties, then try using this.

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

Check this Demo

Upvotes: 6

Enigmativity
Enigmativity

Reputation: 117057

I think this is the fairly straight forward:

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

It gives me:

result

Upvotes: 2

Aleksey L.
Aleksey L.

Reputation: 37918

You can group by Key and select max 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() });

Upvotes: 3

Related Questions