32
1
using System;
2
using System.Linq;
3
using System.Collections.Generic;
4
5
public class Program
6
{
7
public static void Main()
8
{
9
List<Access> lst = new List<Access>();
10
11
//add 2 duplicate records
12
lst.Add(new Access(){id=1,enabled=true} );
13
lst.Add(new Access(){id=1,enabled=true} );
14
lst.Add(new Access(){id=1,enabled=false} );
15
lst.Add(new Access(){id=2,enabled=false} );
16
lst.Add(new Access(){id=2,enabled=false} );
17
18
Dictionary<int,Boolean> newList = lst.GroupBy(x=>x.id).Select(x=>x.First()).ToDictionary(r => r.id, k => k.enabled);
19
20
/*** If ToDictionary is called without GroupBy, then run time error will occur.***/
21
//lst.ToDictionary(r => r.id, k => k.enabled);[System.ArgumentException: An item with the same key has already been added.]
22
23
Console.WriteLine(newList.Count()); //should print 2
24
Console.WriteLine(newList[2]);
25
}
26
27
public class Access{
28
public int id{get;set;}
29
public Boolean enabled{get;set;}
30
}
31
32
}
Cached Result
2
False
False