Just group items by Data1
property:
var groups = recordList.GroupBy(d => d.Data1);
Then you will have items grouped by their Data1
value.
foreach(var data1Group in groups)
{
Console.WriteLine(data1Group.Key); // group key A or B
foreach(var data in data1Group)
Console.WriteLine(data.Data2);
}
Or use lookup
var lookup = recordList.ToLookup(d => d.Data1, d => d.Data2);
// getting items for A
foreach(var data2 in lookup["A"])
Console.WriteLine(data2);
You can skip projecting lookup items
var lookup = recordList.ToLookup(d => d.Data1);
In this case lookup will be like a groups, but with indexed access by key.
Whats wrong in your code? Lets see what it does
var data = recordList.ToLookup(x => x.Data1, (x) =>
{
return (from m in recordList
where m.Data1 == x.Data1
select new MyData { Data2 = m.Data2, Data1 = m.Data1 }).First();
});
It groups items in recordList
by Data1
property value, and for each item in group it puts into lookup following value:
(from m in recordList
where m.Data1 == x.Data1
select new MyData { Data2 = m.Data2, Data1 = m.Data1 }).First()
Result of this query will be same for all items in group - it goes to recordList
finds first item with same Data1
as current item (but not same item!) and creates its copy. Thus you end up with lookup filled with copies of first items in each group.