如何从列表中 return 不同的重复项集

How to return different sets of duplicates from a list

我有以下对象列表:

ConnectionType = ConnectionType.COM
ComPort = "com1"
TcpPort = null
ConnectionName = "CONN0"

ConnectionType = ConnectionType.COM
ComPort = "COM1"
TcpPort = null
ConnectionName = "CONN1"

ConnectionType = ConnectionType.COM
ComPort = "COM1"
TcpPort = null
ConnectionName = "CONN2"

ConnectionType = ConnectionType.COM
ComPort = "COM2"
TcpPort = null
ConnectionName = "CONN3"

ConnectionType = ConnectionType.IP
ComPort = null
TcpPort = 1234
ConnectionName = "CONN4"

ConnectionType = ConnectionType.IP
ComPort = null
TcpPort = 1234
ConnectionName = "CONN5"

ConnectionType = ConnectionType.IP
ComPort = null
TcpPort = 4321
ConnectionName = "CONN6"

每个对象中使用的类型:

private int? tcpPort;
private string comPort;
private string connectionName;
private ConnectionType connectionType;

哪种 LINQ 查询会 return 每个 ConnectionType 的 lookup/dictionary 重复项?结果应包括每个重复项的 ComPort/TcpPort 和 ConnectionName。至于 ComPort,查询也应匹配忽略大小写的字符串。

到目前为止,我已经能够通过以下查询检索到一些理想的结果:

var duplicates = myList
            .GroupBy(x => new { x.ComPort, x.TcpPort }).
            .Where(m => m.Key != null && m.Skip(1).Any());

return以下是:

{ ComPort = COM1, TcpPort =  }
     CONN1
     CONN2
{ ComPort = , TcpPort = 1234 }
     CONN4
     CONN5

但是结果输出应该如下所示:

COM1
    CONN0
    CONN1
    CONN2

1234
    CONN4
    CONN5

您可以使用此 LINQ 查询:

var result = input.GroupBy(x => x.ConnectionType == ConnectionType.IP ? x.TcpPort : x.ComPort)
                  .Where(x => x.Count() > 1)
                  .Select(x => x.Key + "\n" + string.Join("\n",x.Select(y => "\t" + y.ConnectionName)));

首先,我们根据 ConnectionTypeTcpPortComPort 分组。然后我们只使用具有多个项目的组,最后用 Select 子句格式化字符串。

在线演示:https://dotnetfiddle.net/CvvBvl

根据@SomeBody 和@Jonathan Barclay 的建议,我能够编写以下查询来生成所需的输出:

var duplicates = myList
            .GroupBy(x => x.ConnectionType == ConnectionType.IP ? x.TcpPort?.ToString() : x.ComPort.ToUpperInvariant())
            .Where(x => x.Skip(1).Any());

感谢大家的帮助! :)