2013-06-25 76 views
0

喜的特性的子集的一個組合列表說我有對象:的LINQ如何查詢項目的列表基於父項目

public class InvoiceLine 
{ 
} 

public class InvoiceHeader 
{ 
    public char Group { get; set; } 
    public List<InvoiceLine> InvoiceLines { get; set; } 
} 

數據爲他們設置如下:

var invoiceLine1 = new InvoiceLine(); 
var invoiceLine2 = new InvoiceLine(); 
var invoiceLine3 = new InvoiceLine(); 
var invoiceLine4 = new InvoiceLine(); 
var invoiceLine5 = new InvoiceLine(); 
var invoiceLine6 = new InvoiceLine(); 
var invoiceLine7 = new InvoiceLine(); 
var invoiceLine8 = new InvoiceLine(); 

var invoiceHeader1 = new InvoiceHeader { Group = 'A', InvoiceLines = new List<InvoiceLine> { invoiceLine1, invoiceLine2 } }; 
var invoiceHeader2 = new InvoiceHeader { Group = 'A', InvoiceLines = new List<InvoiceLine> { invoiceLine3, invoiceLine4 } }; 
var invoiceHeader3 = new InvoiceHeader { Group = 'B', InvoiceLines = new List<InvoiceLine> { invoiceLine5, invoiceLine6 } }; 
var invoiceHeader4 = new InvoiceHeader { Group = 'B', InvoiceLines = new List<InvoiceLine> { invoiceLine7, invoiceLine8 } }; 

var invoiceHeaders = new List<InvoiceHeader> 
{ 
    invoiceHeader1, 
    invoiceHeader2, 
    invoiceHeader3, 
    invoiceHeader4 
}; 

我想要得到的是每個組的invoiceLines列表。

所以我想爲A組:

invoice1invoice2invoice3invoice4

和B組:

invoice5invoice6invoice7invoice8

最遠的我得到是:

var invoiceLinesGroupA = invoiceHeaders.SelectMany(x => x.InvoiceLines); 

據我所知,將得到所有八個invoiceLines。不知何故,我需要按羣組進行區分,以獲得組A的組羣,併爲組B做同樣的事情。

任何人都可以幫忙嗎?

回答

1

你可能只是想組由該組的發票標題:

var groups = invoiceHeader.GroupBy(ih => ih.Group); 

然後你就可以訪問該組的線路:

foreach(var group in groups) 
{ 
    Console.WriteLine("Group " + group.Group); 
    Console.WriteLine("Lines:"); 
    Console.WriteLine(string.Join(", ", group.SelectMany(h => h.InvoiceHeader.InvoiceLines))); 
} 

輸出會是這樣的

Group A 
Lines: 
invoice1, invoice2, invoice3, invoice4 

Group B 
Lines: 
invoice5, invoice6, invoice7, invoice8 
0
var regrouped = invoiceHeaders 
    .SelectMany(
     header => header.InvoiceLines, 
     (header, line) => new { header, line } 
    ) 
    .GroupBy(
     o => o.header.Group, 
     o => o.line, 
     (groupName, lines) => new InvoiceHeader 
     { 
      Group = groupName, 
      InvoiceLines = lines.ToList() 
     } 
    ) 
    .ToList(); 
0

看看這個過載的Enumerable.SelectMany

var result = invoiceHeaders 
       .SelectMany(x => x.InvoiceLines, 
          (group, InvoiceLine)=>{group, InvoiceLine}) 
       .Where(res => res.group='A'); 
+0

試過這個不會編譯 – user2005657

0

這應做到:

 var test = from h in invoiceHeaders 
        from i in h.InvoiceLines 
        group i by h.Group 
        into g 
        select new {key = g.Key, rows = g.ToArray()}; 

然後,您可以像這樣訪問test.Where(x => x.key == 'A').rows

0
var q = from current in myInvoiceHeaders 
       join c in myInvoiceLines on current.Id equals c.Header.Id into linesByHeader      
       select new { 
        Header = current, 
        Lines = linesByHeader 
       }; 

的項目,你有一個標準的前提下,應該工作加入兩個實體。

相關問題