Return 0 if no duplicates found from DistinctBy

203 Views Asked by At

I thought this would have been simple, but unfortunately I cannot find an answer to what I'm looking for. What I'd like to achieve, is return a list of distinctive results if they're duplicated, otherwise return 0 instead of singular items. The code I have so far is, where the first distinct by should return all distinct rows, and then the second one filter them further down:

List<Server> serversWithBothAffinity = filteredServers
    .DistinctBy(x => new { x.ServerVersion, x.ServerName, x.ServerSlot, x.ServerAffinity})
    .DistinctBy(x => new {x.ServerVersion, x.ServerName, x.ServerSlot});

The problem with this is, when I have just 1 item in the list which has no duplicates - this code still returns 1, when I want it to return 0.

Happy day scenario, when its all working as I want, given the following:

{1.0, "ServerName1", "ServerSlotA", "Europe"}
{1.0, "ServerName1", "ServerSlotA", "Pacific"}
{1.0, "ServerName2", "ServerSlotB", "Europe"}
{1.0, "ServerName2", "ServerSlotA", "Pacific"}

Result is correct as expected:

{1.0, "ServerName1", "ServerSlotA"}

Problem scenario, given the following:

{1.0, "ServerName1", "ServerSlotA", "Europe"}

Result is incorrect:

{1.0, "ServerName1", "ServerSlotA"}

Expected Result: nothing

Please help.

1

There are 1 best solutions below

2
On BEST ANSWER

You don't need MoreLINQ here:

List<Server> serversWithBothAffinity = filteredServers
    .GroupBy(x => new { x.ServerVersion, x.ServerName, x.ServerSlot})
    .Where(g => 1 < g.Count())
    .Select(g => g.First())
    .ToList();

The problem with DistinctBy is that after applying it you can't tell how many items was in each 'group' - it will produce single item


You can also use nice query syntax (well, except ToList part)

var serversWithBothAffinity = 
      from s in  filteredServers
      group s by new { s.ServerVersion, s.ServerName, s.ServerSlot} into g
      where 1 < g.Count()
      select g.First();