C
C#2y ago
Esa

❔ Need help with a LINQ query

Hi, I could use a bit of help building a LINQ query. Assume a simple entity like this:
Event
int EventTypeId
int CustomerId
Event
int EventTypeId
int CustomerId
Then you have an IEnumerable<Event>. From this collection I want to extract all customer ids that only have eventTypeId == 1 associated with them. So if there are two events for one customerId, and those two eventTypeIds are 1 and 2 then I don't want that associated customer id. If both eventTypeIds are 1 then I want that specific customerId. Does that make sense? Currently I have this
from event in events
group event by event.CustomerId
into customerEvents
where customerEvents.All(event => event.EventTypeId != 2)
select customerEvents
from event in events
group event by event.CustomerId
into customerEvents
where customerEvents.All(event => event.EventTypeId != 2)
select customerEvents
But looking at it it doesn't really make sense. And it doesn't return what I thought it would. Any ideas?
13 Replies
Angius
Angius2y ago
events
.Where(e => e.EventTypeId == 1)
.GroupBy(e => e.CustomerId)
.Where(g => g.Count() == 1)
.Select(g => g.Key.CustomerId);
events
.Where(e => e.EventTypeId == 1)
.GroupBy(e => e.CustomerId)
.Where(g => g.Count() == 1)
.Select(g => g.Key.CustomerId);
Something like this should work Ah, wait, you want events with typeid 2 as well
Esa
Esa2y ago
Oh hang on I think I mixed up my instruction 🙂 I'll verify it, hang on a bit..
Angius
Angius2y ago
This code only gives you ones that have EventTypeId equal to 1, and deduplicates it by customer ID
Esa
Esa2y ago
events
.Where(e => e.EventTypeId == 1)
events
.Where(e => e.EventTypeId == 1)
Would this imply that there may exist events with EventTypeId == 2 for a given customerId, but that we just filter them out? Because if they exist in the collection, then I can't use that specific customerId
Angius
Angius2y ago
It gets all events where EventTypeId is 1 Doesn't care about customer IDs
Esa
Esa2y ago
Ok, I think we need to be more specific. A customerId may have several events associated with them. Several 1s or several 2s or a mix of both. If there is any 2 at all, then all of the 1s for that customer id are unusable.
Angius
Angius2y ago
Ah, gotcha You'd need to group by user ID first, then
Esa
Esa2y ago
Ah, okay
Angius
Angius2y ago
Then, in each group, check if an event with type ID 1 exists And filter accordingly
Esa
Esa2y ago
events
.GroupBy(e => e.CustomerId)
.Where(g => g.All(e => e.EventTypeId != 2))
.Select(g => g.Key.CustomerId);
events
.GroupBy(e => e.CustomerId)
.Where(g => g.All(e => e.EventTypeId != 2))
.Select(g => g.Key.CustomerId);
So something like this?
Angius
Angius2y ago
Something like that, yeah
ero
ero2y ago
i wish linq had a None, but i understand why it doesn't
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.