I have a list that I want to group by property A. Then select all the elements for that group where the GroupBy key is null or '' then I want to return all the elements for those groups. Otherwise, for a group key return the first element of that group. I have come up with the following and what I expect from code. Any help would be much appreciated.
Sample code:
public class ABC
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
var list = new List<ABC>()
{
new ABC() { A = "a", B = "b", C = "c" },
new ABC() { A = "a", B = "b", C = "c" },
new ABC() { A = null, B = "b", C = "c" },
new ABC() { A = null, B = "b", C = "c" },
new ABC() { A = "", B = "b", C = "c" },
new ABC() { A = "", B = "b", C = "c" },
};
var result = list.GroupBy(x => x.A)
.Select(x =>
{
if (!string.IsNullOrEmpty(x.Key))
return x.First();
else
return x;
})
.ToList();
What I expect:
I am expecting to see a total of 5 count from the result
{ A = "a", B = "b", C = "c" } count 1 (1 removed)
{ A = null, B = "b", C = "c" } count 2 (none removed)
{ A = "", B = "b", C = "c" } count 2 (none removed)