Return 0 if no duplicates were found from DistinctBy

I thought it would be simple, but unfortunately I can not find the answer to what I am looking for. What I would like to achieve is to return a list of distinctive results if they are duplicated, otherwise return 0 instead of special elements. The code that I still have is that the first individual element should return all the individual rows, and then the second filters them further:

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 that when I have only one item in the list that has no duplicates - this code still returns 1 when I want it to return 0.

The Happy Day scenario when everything works the way 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"}

The result is correct as expected:

{1.0, "ServerName1", "ServerSlotA"}

Problem scenario given the following:

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

The result is incorrect:

{1.0, "ServerName1", "ServerSlotA"}

:

, .

+4
1

MoreLINQ:

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

DistinctBy , , -


(, ToList)

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();
+3

Source: https://habr.com/ru/post/1669330/


All Articles