我有一個 <int, string> 字典,我正在嘗試檢查一個 IEnumerable 物件以查看字典中是否包含特定屬性。我知道包含,但如果它有意義,我似乎無法扭轉它。
如果它只是一個值,我會很好,但我需要串列來遍歷串列中每個專案的整個字典。
目前我正在使用這個:
foreach (var item in model)
{
if (dictionary.Values.Contains(object.Attribute))
{
list.Add(object);
}
}
謝謝!
uj5u.com熱心網友回復:
看看下面的代碼,如果你想玩它,請使用這個 Fiddle。這需要 Jon Skeet 的建議來使用HashSet.
// your dictionary of items
var dict = new Dictionary<int, string>();
dict.Add(0, "Zero");
dict.Add(2, "Two");
dict.Add(4, "Four");
// as suggested by Jon Skeet, create a HashSet to be more performant
var hs = new HashSet<string>(dict.Values);
// list of unfiltered items
var list = new List<dynamic>()
{
new { Id = 0, Name = "Zeroth", PropertyYouWantToCheck = "Zero" },
new { Id = 1, Name = "First", PropertyYouWantToCheck = "One" },
new { Id = 2, Name = "Second", PropertyYouWantToCheck = "Two" },
new { Id = 3, Name = "Third", PropertyYouWantToCheck = "Three" },
new { Id = 4, Name = "Fourth", PropertyYouWantToCheck = "Four" },
};
// LINQ query to filter the list
var filteredList = list.Where(i => hs.Contains(i.PropertyYouWantToCheck));
// output the name of the filtered items
Console.WriteLine(string.Join(", ", filteredList.Select(fl => fl.Name)));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510707.html
標籤:C#。网林克字典
