2017-01-06 18 views
2

タイトルが意味をなさないことを願っています。子要素との一致に基づいて要素を返すLINQ

親要素のプロパティと一致しない子オブジェクトの子オブジェクトのすべての要素を返すLINQクエリを生成しようとしています。

うまくいけば、私はその説明であなたを失っていないと思います。私は具体的な例が私が何をしようとしているのかを説明するのに役立つかもしれないと思う。

私は三つのクラスと列挙型があります。

public class Studio 
{ 
    public int StudioId { get; set; } 
    public string StudioName { get; set; } 
    public Style Style { get; set; } 

    public virtual ICollection<Designer> Designers { get; set; } 
} 

public class Designer 
{ 
    public int DesignerId { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public int StudioId { get; set; } 

    public virtual Studio Studio { get; set; } 
    public virtual ICollection<Product> Products { get; set; } 
} 

public class Product 
{ 
    public int ProductId { get; set; } 
    public string ProductName { get; set; } 
    public decimal Price { get; set; } 
    public int DesignerId { get; set; } 
    public Style ProductStyle { get; set; } 

    public virtual Designer Designer { get; set; } 
} 

public enum Style { Classic, Preppy, Modern, Punk, Goth } 

を各スタジオには、その全体的なStyleがあり、それぞれProductは、独自のスタイルを持っています。 Productが一致しないスタイルの哲学でStudioに表示される場合があります。

クエリが一致しないStudioにあるProductsを含むIEnumberable<Product>を返すクエリを生成することはできますか。

私が働くトリプルネストされたループを作成しましたが、私は(ドット表記を使用して)LINQ文の中にそれを変換するいくつかの助けを期待していた:

public IEnumerable<Product> GetProductsWithOutsideStyles(Studio studio) 
{ 
    List<Product> products = new List<Product>(); 

    foreach (Studio s in StudioContext.Studios.Where(s => s == studio)) 
    { 
     foreach(Designer d in s.Designers) 
     { 
      foreach(Product p in d.Products) 
      { 
       if (p.ProductStyle != s.Style) 
        products.Add(p); 
      } 
     } 
    } 
    return products; 
} 

答えて

2

あなたはAに属する製品にアクセスできますStudioに移動します。それはProduct.ProductStyleStudio.Style間のミスマッチをチェックするのは簡単ですその後:

from s in context.Studios 
where s.StudioId == studio.StudioId 
from d in s.Designers 
from p in d.Products 
where p.ProductStyle != s.Style 
select p 

ところで、あなたは、idでStudioを見つける必要があります。 EFでは、LINQクエリでstudio変数を使用することはできません。

1

試してみてください。

var products=studios.SelectMany(s => s.Designers 
      .SelectMany(d => d.Products.Where(p => p.ProductStyle != s.Style))) 
       .ToList(); 
1

は、 "ネストされた" リスト

.SelectMany()拡張メソッドに相当)

var products = 
     from s in StudioContext.Studios.Where(s => s == studio) 
     from d in s.Designers 
     from p in d.Products 
     where p.ProductStyle != s.Style 
     select p; 
を使用してクエリを作成するために、複数の from文とSQLスタイルのLINQの構文を使用することを検討してください

拡張メソッドも有効です。ネストされたリストの場合、私は個人的には、あなたの意図を表現するためには、SQLスタイルの構文がもっとはっきりと(読みやすい)ことがわかります。ネスティングが複数のレベルにある場合、.SelectManyはやや明確ではありません。

関連する問題