C#根据列表属性从自定义对象列表中过滤出重复项

时间:2019-02-19 08:54:18

标签: c# linq

我有一个List<IPInfo>个自定义IPInfo对象。我需要根据此类的两个属性过滤出重复项。

这是一堂课:

class IPInfo
{
    public String TRADE_DATE; 
    public String CUSTOMER_NAME;
    public List<String> ORIGINAL_IP;
    public List<String> LOGON_IP = new List<String>();
}

List<IPInfo> fields的记录具有相同的CUSTOMER_NAMELOGON_IP。我要删除它们,以确保具有相同CUSTOMER_NAME的条目具有不同的LOGON_IP

我根据其他发布的答案尝试了LINQ。但是此代码未编译。

    private static List<IPInfo> selectFields(ref List<IPInfo> fields)
    {
        var distinct = fields.GroupBy(x => new { x.CUSTOMER_NAME, x.LOGON_IP })
                .Select(y => new IPInfo()
                {
                    TRADE_DATE = y.Key.TRADE_DATE,
                    CUSTOMER_NAME = y.Key.CUSTOMER_NAME,
                    ORIGINAL_IP = y.ToList(),
                    LOGON_IP = y.ToList()
                }
                ).ToList();

        return distinct;
    }

请给我一些提示。

Trade_date Customer_name Original_IP Logon_IP

enter image description here

2 个答案:

答案 0 :(得分:4)

您可以尝试GroupByFirst(如果我们有重复的 group 组,则应仅使用 first 项)。

另一个问题是如何按List<T>分组(LOGON_IP是列表);假设LOGON_IP相等,且仅当它们具有相同顺序的相同项目时,我们才能 在LOGON_IP的帮助下将string变成string.Join;如果LOGON_IP中的顺序无关紧要,我们可以使用

string.Join(" ", x.LOGON_IP.OrderBy(ip => ip))

代码:

private static List<IPInfo> selectFields(ref List<IPInfo> fields)
{
    var distinct = fields 
      .GroupBy(x => new { x.CUSTOMER_NAME, ips = string.Join(" ", x.LOGON_IP) })
      .Select(chunk => chunk.First())
      .ToList();

    return distinct;
}

编辑::如果我们根本不想返回重复的 (即,如果项目重复,则应删除所有出现的 ),让我们检查Count

private static List<IPInfo> selectFields(ref List<IPInfo> fields)
{
    var distinct = fields 
      .GroupBy(x => new { x.CUSTOMER_NAME, ips = string.Join(" ", x.LOGON_IP) })
      .Where(chunk => chunk.Count() == 1)
      .Select(chunk => chunk.First())
      .ToList();

    return distinct;
}

答案 1 :(得分:4)

给它一个裂缝:

private static List<IPInfo> selectFields(ref List<IPInfo> fields)
{
    var distinct =
        fields
            .GroupBy(x => new { x.TRADE_DATE, x.CUSTOMER_NAME })
            .Select(y => new IPInfo()
            {
                TRADE_DATE = y.Key.TRADE_DATE,
                CUSTOMER_NAME = y.Key.CUSTOMER_NAME,
                ORIGINAL_IP = y.SelectMany(x => x.ORIGINAL_IP).Distinct().ToList(),
                LOGON_IP = y.SelectMany(x => x.LOGON_IP).Distinct().ToList()
            })
            .ToList();

    return distinct;
}