我有以下模型类:
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的列表项?
答案 0 :(得分:1)
首先,没有"二维列表"在.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://msdn.microsoft.com/en-us/library/bb545971.aspx
答案 1 :(得分:1)
这应该有效:
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);
答案 2 :(得分: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);
}