I have some data returned as the follow:
Model { Guid Id }
and I have an int of the total items, int totalCount
.
I am trying to get the distinct count from the data that were returned as Category 1, and have the total item minus the count from Category 1 to be Category 2.
I have the following linq to get the distinct count for Category 1, but how do I add the count for Category 2 into the IEnumerable?
var result = data.
GroupBy(x => x.Id).
Select(x => new { Category = "1", Value = x.Select(v => v.Id).Distinct().Count() }).
GroupBy(x => x.Category).
Select(x => new Item { Category = x.Key, Value = x.Sum(y => y.Value) });
and the Item Class have 2 members: string for Category and decimal for Value.
Thanks!
Edit:
So I have the follow data IEnumerable<Model> data
, and it contains the following data:
{ Id: 1 }
{ Id: 2 }
{ Id: 2 }
{ Id: 1 }
{ Id: 3 }
{ Id: 4 }
and totalCount = 10.
I would like to get the distinct count of Id from data, which is 4 in this case, as category 1, and totalCount - distinct item to be category 2. So for the result I will have a IEnumerable
of Item
to have the following:
{ Category: "1", Value: 4 }, { Category: "2", Value: 6 }
For now my linq statement only return { Category: "1", Value: 4 }
, and I have no idea what to do next.
Your question is not very clear, but I think this is what you want:
int totalCount = data.Count();
int distinctCount = data.Select(x => x.Id).Distinct().Count();
List<Item> result = new List<Item>
{
new Item() { Category = "1", Value = distinctCount },
new Item() { Category = "2", Value = totalCount - distinctCount },
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With