1

LINQ でできるかどうかわからないことをしようとしていますが、試してみましょう! 私には2つのクラスがあります。一方は他方のリスト構造です。

public class1 {
    public int id {get; set;}
    public string title {get; set;}
    public List<class2> subcat {get; set;}
}
public class2 {
    public int Value {get; set;}
    public string Text {get; set;}
}

そのような構造をLINQで埋めることは可能ですか? 何かのようなもの:

return (from r in results 
    from sub in subresults.Where(sub => sub.id == r.subid).DefaultIfEmpty()
    select new class1  {
        id = r.id,
        title = r.title,
        subcat = [GET TWO COLUMNS FROM 'SUB' INTO THIS]
    }).ToList()

これは可能ですか?ネストされたループなどを使用して手動で構築する必要はありません。
よろしくお願いします!

4

2 に答える 2

3

これはあなたが必要とするものですか?

return (from r in results 
    select new class1  {
        id = r.id,
        title = r.title,
        subcat = (from sub in subresults
                 where sub.id == r.subid
                 select new class2 { Value = sub.Value, Text = sub.Text }).ToList()

    }).ToList()
于 2012-08-10T21:05:02.610 に答える
0

You can use a navigation property to load results and subresults in one query.

from r in results
select new class1  {
    id = r.id,
    title = r.title,
    subcat = r.Subresults.Select(sr =>
             new class2 { Value = sr.Value, Text = sr.Text })

...assuming that the navigation property result.Subresults exists or otherwise can be created for convenience.

AutoMapper could also be useful here. If yo define two mappings (result => class1, subresult => class2) it will load the nested collection automatically.

于 2012-08-10T21:19:14.107 に答える