2016-05-20 8 views
0

私は結合を使用しようとしませんでしたが、今日は結合を使用して複雑な状況を修正したい、私は例の下にリストされているデータを持っています。私もコメントを入れた。さらに進めるには?C#のリストのリストに登録

namespace JoinsApplication 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<Category> categories = new List<Category>() 
      { 
       new Category(){Name="Beverages", ID=001,Products =new List<Product>(){new Product{Name="Cola", CategoryID=001},new Product{Name="Tea", CategoryID=001} } }, 
       new Category(){ Name="Condiments", ID=002,Products =new List<Product>(){new Product{Name="Mustard", CategoryID=002},new Product{Name="Pickles", CategoryID=003} } }, 
       new Category(){ Name="Vegetables", ID=003,Products =new List<Product>(){new Product{Name="Carrots", CategoryID=003},new Product{Name="Melons", CategoryID=003} } }, 
       new Category() { Name="Grains", ID=004,Products =new List<Product>(){new Product{Name="Carrots", CategoryID=003},new Product{Name="Melons", CategoryID=003} } }, 
       new Category() { Name="Fruit", ID=005,Products =new List<Product>(){new Product{Name="Peaches", CategoryID=005},new Product{Name="Melons", CategoryID=005} } }  
      }; 

      //filter data using join, i want to filter data and want a condition on cat.ID and Product.CategoryID, but Products property is not accessible using category alias. 
      //var u= from cat in categories join product in cat.Products on product.CategoryID equels cat.ID select cat.Name, product.Name; 
     } 
    } 

    #region Join Demonstration data 

    public class Product 
    { 
     public string Name { get; set; } 
     public int CategoryID { get; set; } 
    } 

    public class Category 
    { 
     public string Name { get; set; } 
     public int ID { get; set; } 
     public List<Product> Products { get; set; } 
    } 

    // Specify the first data source. 


    #endregion 

} 
+1

期待されるou tput? –

答えて

2

シンプルです。あなたはただ、これはSelectManyを使用して達成することができ、これを終了した製品の完全なリストが必要になります。

var uu = (from cat in categories 
      join product in categories.SelectMany(p => p.Products) 
      on cat.ID equals product.CategoryID 
      select new 
      { 
       CategoryName = cat.Name, 
       ProductName = product.Name 
      }).ToList(); 

編集(ラムダを使用する):以下

var uuLambda = categories.Join(categories.SelectMany(p => p.Products), 
           cat => cat.ID, prod => prod.CategoryID, 
           (cat, prod) => new { CategoryName = cat.Name, ProductName = prod.Name }).ToList(); 

はあなたのコメントに基づいており、それとにかく良い考えではありません。それは可読ではありません:

var uuWhere = categories.SelectMany(p => p.Products). 
         Select(prod => new { ProductName = prod.Name, 
               CategoryName = categories.Where(x => x.ID == prod.CategoryID). 
                  Select(x => x.Name).FirstOrDefault() }).ToList(); 
+0

ありがとう、ソリューションは私の期待通りに働いています。 –

+0

ラムダ式はどのように使用できますか? ご迷惑をおかけした場合は、ご返信ください。 –

+0

「from」構文を使用しないことを意味しますか? – user3185569

関連する問題