简体   繁体   中英

How verify if a List of Dictionary contains a Dictionary with specific key - C#

I have a List of Dictionaries:

List<Dictionary<string, int>> listDic = new List<Dictionary<string, int>>();

How do I verify if listDic contains a Dictionary with Key == "apple", for example?

You can use .Any on the outer dictionary and .ContainsKey on the inner ones. Something like this:

var containsApple = listDic.Any(x => x.ContainsKey("Apple"));

This should result in true if any one or more of the dictionaries in listDic contains the key "Apple" .

Essentially you start with your overall problem:

How do I verify if listDic contains a Dictionary with Key == "apple"

And break it into two smaller, simpler, easily findable on Google problems:

  1. How do I verify that a dictionary contains a given key?
  2. How do I verify that any one or more elements in a collection meet a condition?

The first one involves calling .ContainsKey on the dictionary, the second one involves calling .Any on the collection. After that, you simply combine the two.

If you can use linq , you can do this by using .Any() :

bool containsKey = listDic.Any(x => x.ContainsKey("apple"));

This checks the collection one by one until the key is found. If the key is found on the second item, .Any() only iterated over two items and not the whole collection.

尝试使用LINQ

bool result = listDic.Any(x => x.ContainsKey("Apple"));
bool contains = listDic.Any(x => x.ContainsKey("apple"));
List<Dictionary<string, int>> listDic = new List<Dictionary<string, int>>();
            Dictionary<string, int> di = new Dictionary<string, int>();
            di.Add("apple", 1);
            listDic.Add(di);

            di = new Dictionary<string, int>();
            di.Add("mango", 2);

            di = new Dictionary<string, int>();
            di.Add("grapes", 3);

            Dictionary<string, int> item = listDic.Where(c => c.ContainsKey("apple")).FirstOrDefault();
            if (item != null)
            {
                string key = item.FirstOrDefault().Key;
                int value = item.FirstOrDefault().Value;
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM