Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq distinct count

Tags:

c#

linq

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.

like image 322
user1628865 Avatar asked Aug 27 '12 22:08

user1628865


1 Answers

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 },
};
like image 158
david.s Avatar answered Oct 08 '22 20:10

david.s