[英]Dropdown Select Distinct based on Text property in a List
我有一個要求,我需要獲得一個唯一/不同項目的列表作為我的下拉值。 請參見下面的示例,
示例數據
Id Text
1 AAA
2 BBB
3 AAA
4 CCC
5 BBB
我希望結果列表應該是
Id Text
1 AAA
2 BBB
4 CCC
我到目前為止嘗試過
var Value = (from x in db.Items
where ((x.CallNo.StartsWith(q) || x.CallNo.Contains(" " + q)) && (!string.IsNullOrEmpty(x.CallNo)))
select new
{
id = x.Id,
text = x.CallNo
}).Distinct().ToList();
意思是,我希望列表基於Text屬性來區分。 而且,這是第一次出現。
您可以簡單地使用GroupBy
和First
:
var Value = db.Items
.Where(x => x.CallNo.StartsWith(q) || x.CallNo.Contains(" " + q)) && !string.IsNullOrEmpty(x.CallNo))
.GroupBy(x => x.CallNo)
.Select(g => g.First())
.Select(x => new
{
id = x.Id,
text = x.CallNo
})
.ToList();
如果您實際上想要通過多個屬性獲取不同的對象,如標題所示,請在GroupBy
使用匿名類型。
.GroupBy(x => new { x.CallNo, x.OtherProperty})
如果要在多個屬性上定義組,請按以下步驟操作:
List<something> myList= employee.GroupBy(p => new {p.employeeId, p.employeeName} )
.Select(g => g.First())
.ToList();
Distinct
有一個需要IEqualityComparer<TSource>
的重載。 因此,您可以編寫一個比較器並提供它。
或者,您可以編寫DistinctBy
(擴展名)方法。 您可以在Jon Skeet的MiscUtil庫中找到它。 但是您也可以輕松地自己編寫:
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source,
Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer = null)
{
var found = new HashSet<TKey>(comparer);
return source.Where(element => found.Add(keySelector(element)));
}
編輯:我實際上是說MoreLinq庫 ,但是MiscUtil也很有用。
請注意,此方法適用於IEnumerable
,而不適用於IQueryable
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.