[英]Linq query to use a list of lists to filter a list
I'm still learning LINQ, and I'm attempting to use an object from one list as an identifier to find objects in another list. 我仍在学习LINQ,并且尝试使用一个列表中的对象作为标识符来查找另一个列表中的对象。
I have two lists of objects, similar to my mock-up code below. 我有两个对象列表,类似于下面的模拟代码。 Using LINQ, I want to list all Colors.Hex of a specific Country's flag color, using the variable selectedCountry. 我想使用LINQ使用变量selectedCountry列出特定国家/地区的标志颜色的所有Colors.Hex。
So if selectedCountry = "USA", I would like to be able to console.write: 因此,如果selectedCountry =“ USA”,我希望能够console.write:
USA
RED FF0000
Blue 0000FF
White FFFFFF
Preferably in query syntax, for readability. 为了可读性,最好在查询语法中。
public class Countries
{
public string Name;
public List<string> FlagColors = new List<string>();
}
public class Colors
{
public string Name;
public string Hex;
}
public partial class Form1 : Form
{
public static List<Countries> country = new List<Countries>();
public static List<Colors> color = new List<Colors>();
public void foo()
{
color.Add(new Colors { Name= "Red", Hex = "FF0000"});
color.Add(new Colors { Name= "Blue", Hex = "0000FF" });
color.Add(new Colors { Name= "White", Hex = "FFFFFF" });
color.Add(new Colors { Name= "Yellow", Hex = "FFFF00" });
Countries newCountry = new Countries();
newCountry.Name = "USA";
newCountry.FlagColors.Add("Red");
newCountry.FlagColors.Add("White");
newCountry.FlagColors.Add("Blue");
country.Add(newCountry);
Countries newCountry2 = new Countries();
newCountry2.Name = "Sweden";
newCountry2.FlagColors.Add("Blue");
newCountry2.FlagColors.Add("Yellow");
country.Add(newCountry2);
string selectedCountry = "USA";
// Linq query here
}
}
Thanks in advance 提前致谢
You can do this like so: 您可以这样做:
Country selectedCountry = country.SingleOrDefault(x => x.Name == selectedCountry);
if (selectedCountry != null) {
Console.WriteLine(selectedCountry.Name);
foreach (string flagColor in selectedCountry.FlagColors) {
Colors color = color.SingleOrDefault(x => x.Name == flagColor);
if (color != null) {
Console.WriteLine(color.Name + " " + color.Hex);
}
}
}
As you can see the LiNQ queries are pretty simple, you basically want to return the first element that matches the condition predicate (in this case, where the Name
is equal to the selectedCountry
or the flagColor
. 如您所见,LiNQ查询非常简单,您基本上想返回与条件谓词匹配的第一个元素(在这种情况下, Name
等于selectedCountry
或flagColor
。
Something like this, perhaps: 大概是这样的:
var q = from c1 in country
from c2 in c1.FlagColors
from c3 in color
where c3.Name == c2 && c1.Name == selectedCountry
select c3.Hex;
Or alternatively: 或者:
var q = from c1 in country
from c2 in c1.FlagColors
join c3 in color on c2 equals c3.Name
where c1.Name == selectedCountry
select c3.Hex;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.