Linq 查询使用列表的列表来过滤列表

Linq query to use a list of lists to filter a list

我仍在学习 LINQ,我正在尝试使用一个列表中的对象作为标识符来查找另一个列表中的对象。

我有两个对象列表,类似于我下面的模型代码。使用 LINQ,我想使用变量 selectedCountry.

列出特定国家/地区国旗颜色的所有 Colors.Hex

因此,如果 selectedCountry = "USA",我希望能够 console.write:

USA
RED FF0000
Blue 0000FF
White FFFFFF

为了便于阅读,最好使用查询语法。

    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
    }
}

提前致谢

您可以这样做:

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);
        }
    }
}

如您所见,LiNQ 查询非常简单,您基本上想要 return 匹配条件谓词的第一个元素(在本例中,Name 等于 selectedCountryflagColor.

可能是这样的:

    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;

或者:

    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;