4

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.

4

1 回答 1

3

您在这里不需要 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();
于 2017-02-10T02:35:42.533 回答