【问题标题】:Find objects in a list where one property contains duplicate values [duplicate]在列表中查找一个属性包含重复值的对象[重复]
【发布时间】:2015-11-17 15:52:20
【问题描述】:

我有以下模型类:

public class DuplicateTags
{
    public string VMName { set; get; }
    public string shortName { set; get; }
}

它被填充如下:

int tempindex = tempvmname.IndexOf('-');
duplicateTagsInDisplayName.Add(new DuplicateTags 
{ 
    VMName = tempvmname, 
    shortName = tempvmname.Substring(0, tempindex)
});

现在我想显示具有重复 shortName 的列表项?

【问题讨论】:

  • 二维列表是什么意思?
  • @jeroenh 一个包含两个字符串对象的列表 ...
  • @dotctor 我可以找到一种方法来做到这一点......否则我会提供我的代码..

标签: c# .net entity-framework


【解决方案1】:

您可以使用 linq 获取重复值

var duplicateShortNames = duplicateTagsInDisplayName
    .GroupBy(x => x.shortName) // items with same shorName are grouped to gether
    .Where(x => x.Count() > 1) // filter groups where they have more than one memeber
    .Select(x => x.Key) // select shortName from these groups
    .ToList(); // convert it to a list

然后您可以检查您的任何项目是否重复并显示它们

foreach (var item in duplicateTagsInDisplayName)
{
    if (duplicateShortNames.Contains(item.shortName))
        Console.WriteLine(item.VMName + item.shortName);
}

【讨论】:

    【解决方案2】:

    首先,.Net 中不存在“二维列表”之类的东西。您有一个DuplicateTags 类型的对象列表,其中DuplicateTag 是一个具有2 个属性的类。

    现在,为了解决您的问题,我建议您学习 LINQ。

    具体来说,您可以为此使用GroupBy

    var groupedByShortName = duplicateTagsInDisplayName.GroupBy(x => x.shortName);
    var duplicates = groupedByShortName.Where(item => item.Count() > 1);
    foreach (var duplicate in duplicates)
    {
        Console.WriteLine("{0} occurs {1} times", duplicate.Key, duplicate.Count);
        foreach (var item in duplicate)
        { 
            Console.WriteLine("   {0}", item.VMName);
        } 
    }
    

    在此处阅读更多信息:https://docs.microsoft.com/en-us/dotnet/csharp/linq/group-query-results

    【讨论】:

      【解决方案3】:

      这应该可行:

      var list = new []{ 
                      new{ VMName = "a", shortName = "sn1" },
                      new{ VMName = "a", shortName = "sn2" },
                      new{ VMName = "b", shortName = "sn1" },
      };
      
      var groupedList = list.GroupBy(x => x.shortName)
                                 .Select(x => 
                                              new{ 
                                                   ShortName = x.Key, 
                                                   Items = x,                                             
                                                   Count = x.Count()
                                                 }
                                        );
      
      var onlyDuplicates = groupedList.Where(x => x.Count > 1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-25
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多