How to get key value based on id from list of dictionaries?

This is my code

public class model 
{
    public model();
    public List<Dictionary<string, string>> Data { get; set; }
}

List<Dictionary<string,string>> data1;

var data1 = await get<model>();

data1[0]=[0][{id,101}]
         [1][{name,one}]

data1[1]=[0][{id,102}]
         [1][{name,two}]

data1[2]=[0][{id,103}]
         [1][{name,three}]

In the code i have a list of dictionaries with id and name keys. now i have id=102 search in list of dictionaries and get name value related on id using linq query.

Upvotes: 0

Views: 2570

Answers (2)

Sandip
Sandip

Reputation: 987

Try this

List<Dictionary<string, string>> data1 = new List<Dictionary<string, string>>();


            Dictionary<string, string> dic1 = new Dictionary<string, string>();
            dic1.Add("101", "one");
            dic1.Add("102", "two");
            data1.Add(dic1);

            dic1 = new Dictionary<string, string>();
            dic1.Add("201", "2one");
            dic1.Add("202", "2two");
            data1.Add(dic1);

            dic1 = new Dictionary<string, string>();
            dic1.Add("301", "3one");
            dic1.Add("302", "3two");
            data1.Add(dic1);

            //try your values here
            var id = "201";
            var s=data1.Where(c => c.Keys.Contains(id)).Select(c => c.Keys.Where(p => p == id).Select(p => c[p]).FirstOrDefault()).FirstOrDefault();
            Console.WriteLine(s);

Upvotes: 0

Eren Ers&#246;nmez
Eren Ers&#246;nmez

Reputation: 39085

var name = data1.First(d => d["id"] == "102")["name"];

You find the first list element where the key "id" maps to value "102", and then get the value for key "name".

Upvotes: 1

Related Questions