Below are the records where we are trying to group the records by the following OR
conditions:
- Name is same
- Email is same
- Phone is same
Is there a way in LINQ to Group By
with Or
condition?
Name Email Phone Id
--- --------- ------------ ----------
Rohan rohan@s.com NULL 1
R. Mehta rohan@s.com 9999999999 2
Alex alex@j.com 7777777777 3
Lisa John john@j.com 6666666666 4
Lisa lisa@j.com 6666666666 5
Siri siri@s.com NULL 6
RM info@s.com 9999999999 7
Lisa NULL NULL 8
Lisa John m@s.com 7777777757 9
Output Expected
Group 1:
Key: Rohan
RecordIds: 1,2,7 (As `Id:1` has same email as `Id:2`, `Id:2` has same
phone number as `Id:7`.)
Group 2:
Key: Lisa John
RecordIds: 4,5,8,9 (As `Id:4` has same phone number as `Id:5`. While `Id:5`
has the same name as `Id:8`. As `Id:9` has the same name
as `Id: 4`, include that)
- 3 and 6 are not part of the output as the output are only group with more than 1 record
- Key can be anything I just put in a random key.
If record 9 had email-id: rohan@s.com
then:
Output
Group 1:
Key: Rohan
RecordIds: 1,2,7,4,5,8,9
NOTE: Input is SQL table
to be read through LINQ to SQL
. So query performance too has to be taken into account.
Crud Solution:
A dirty solution would be the following:
- Group the records by Name -> store result in
var gl-1
- Group the records by Email -> store result in
var gl-2
- Group the records by Phone -> store result in
var gl-3
- Take each result in
gl-1
check if correspondingid
is present ingl-2
,gl-3
. If so include thoseids
ingl-1
- Take each result in
gl-2
check if correspondingid
is present in any result ingl-1
is so, include the exclusiveids
togl-1
record. If the loop encounters a result which is not present ingl-1
, include it as a result ingl-1
. - Do step 5 for
gl-3
.