2017-02-11 164 views
0

我仍然在学习LINQ,我试图使用一个列表中的对象作为标识符来查找另一个列表中的对象。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 
    } 
} 

在此先感谢

回答

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等于selectedCountryflagColor

+0

谢谢。得到的代码工作,它做我想要的。是的,这似乎很简单,只是要学习语法。这有助于一路。干杯! – Caliber

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;