Reputation: 9999
My Super
class property is
public List<Test> Super { get; set; }
while myTest
class is
public class Test
{
public int Id { get; set; }
public Dictionary<string, string> dict { get; set; }
}
How can i select all values from the dictionary where the key name is "description"
Upvotes: 3
Views: 2234
Reputation: 7600
You can do something like
var dict = (from p in obj.Super
where p.dict != null && p.dict.ContainsKey(keyToCheck)
select p.dict[keyToCheck]);
Complete code:
void Main()
{
string keyToCheck = "description";
var obj = new Super1();
var dict = (from p in obj.Super
where p.dict != null && p.dict.ContainsKey(keyToCheck)
select p.dict[keyToCheck]);
Console.Write(dict);
}
public class Super1
{
public List<Test> Super { get; set; } = new List<Test>(){
new Test(){ Id = 1, dict = new Dictionary<string,string>() {
{"description","abc"},{"description1","1"},{"description2","2"},{"description3","3"}
}},
new Test(){ Id = 2, dict = new Dictionary<string,string>() {
{"description","xyz"},{"description4","4"},{"description5","5"},{"description6","6"}
}
}};
}
public class Test
{
public int Id { get; set; }
public Dictionary<string, string> dict { get; set; }
}
Output:
abc
xyz
Upvotes: 1
Reputation: 1600
You can try is
List<string> AllValues = new List<string>();
Super.ForEach(x =>
{
if(x.dict.ContainsKey("description")
{
AllValues.AddRange(x.dict["description"]);
}
});
Upvotes: 0
Reputation: 119176
You can use SelectMany
to get all the dictionaries, for example:
var values = Super
.SelectMany(s => s.dict)
.Where(s => s.Key == "description")
.Select(s => s.Value);
Upvotes: 5