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

时间:2017-02-11 00:41:48

标签: c# linq linq-to-objects

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

我有两个对象列表,类似于下面的模拟代码。使用LINQ,我想使用变量selectedCountry列出特定Country的标志颜色的所有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
    }
}

提前致谢

2 个答案:

答案 0 :(得分:2)

你可以这样做:

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查询非常简单,您基本上希望返回与条件谓词匹配的第一个元素(在这种情况下,Name等于selectedCountry或者flagColor

答案 1 :(得分:1)

这样的事情,也许是:

    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;
相关问题