![](/img/trans.png)
[英]How to find all items in a list where a property has a specific value or where there is a related item with this value?
[英]Is there a Linq operation to retrieve specific items from a list of items where the item has a property value for a property which should be unique?
我有一個自定義對象的List<>
。 此自定義類型具有一個名為Name
的屬性,該屬性在列表中應該是唯一的。 換句話說,列表中沒有2個項目的Name
屬性應具有相同的值。
當我驗證此列表時,我想檢索有問題的項目。 是否有Linq手術可以使我做到這一點?
我想要類似的東西
listOfItems.Where(x => x.Name.Equals(/*anything else in this list with the same value for name */)
基本上,我試圖避免對照列表中的每個項目(在嵌套的foreach中)檢查整個列表:
private IList<ICustomObject> GetDuplicatedTypeNames(IList<ICustomObjects> customObjectsToFindDuplicatesIn)
{
var duplicatedList = new List<ICustomObject>();
foreach(var customObject in customObjectsToFindDuplicatesIn)
foreach(var innerCustomObject in customObjectsToFindDuplicatesIn)
if (customObject == innerCustomObject && customObject .Name.Equals(innerCustomObject.Name))
duplicatedList.Add(customObject);
return duplicatedList;
}
(編輯)注意:我受域規則的約束,只能使用List <>,而不能選擇使用Dictionary <>。
獲取重復的名稱:
var duplicates = listOfItems
.GroupBy(i => i.Name)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
編輯:獲取重復項:
var duplicates = listOfItems
.GroupBy(i => i.Name)
.Where(g => g.Count() > 1)
.SelectMany(g => g);
為什么不以Name屬性作為鍵,而使用Dictionary而不是List? 這樣,您根本無法向集合中添加重復的名稱,因為會引發異常。
此外,在添加名稱之前,可以使用ContainsKey方法測試名稱是否在詞典中。
這種方法的優勢在於,它比掃描列表中的重復項要快得多。
這將返回對象列表
class foo
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
class fooEqualityComparer : IEqualityComparer<foo>
{
public bool Equals(foo x, foo y)
{
if (x == null || y == null)
return false;
return x.Name == y.Name;
}
public int GetHashCode(foo obj)
{
return obj.Name.GetHashCode();
}
}
var duplicates = listOfItems
.GroupBy(x => x, new fooEqualityComparer())
.Where(g => g.Count() > 1)
.SelectMany(g => g);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.