2013-05-29 187 views
1

我有一個具有重複值的對象的集合。可以說,對象是:使用linq合併集合

public InvoiceCompany 
{ 
    public decimal InvoiceValue { get; set; } 
    public string Company { get; set; } 
} 

並且我有List集合中每個公司的多個發票。如何合併集合中的對象,不同公司並同時添加他們的InvoiceValues?我想用Linq來做!

+1

什麼是你想要的最終輸出?匿名類型?它將包含哪些屬性? – haim770

+1

你有什麼嘗試嗎?如果是這樣,請發佈代碼和它有什麼問題。如果不是:爲什麼不呢? –

+0

您能給我們一個輸入和預期輸出的例子嗎? –

回答

6

使用GroupBy

var list = new List<InvoiceCompany>(); //your collection of invoices 
var grouped = list.GroupBy(x => x.Company) 
        .Select(g => new InvoiceCompany { Company = g.Key, InvoiceValue = g.Sum(x => x.InvoiceValue) }); 
+0

我認爲'Select'應該看起來像這樣:'Select(g = new InvoiceCompany {Company = g.Key,InvoiceValue = g.Sum(x => x .InvoiceValue)})'。原因:該操作說明:*「同時添加他們的發票價值」* –

+0

你是對的,謝謝:)。現在編輯。 – gzaxx

2

您可以通過語句中使用的一組。

List<InvoiceCompany> li = new List<InvoiceCompany>(){ 
    new InvoiceCompany { Company = "a", InvoiceValue = 1 }, 
    new InvoiceCompany { Company = "a", InvoiceValue = 2 }, 
    new InvoiceCompany { Company = "b", InvoiceValue = 1 }, 
    new InvoiceCompany { Company = "b", InvoiceValue = 2 } 
}; 

var v = from a in li 
     group a.InvoiceValue by a.Company into b 
     select new { Company = b.Key, Invoices = b.ToList().Sum() }; 
0

由公司嘗試組的InvoiceValue並計算總和:

var v = 
from l in list 
group l.InvoiceValue by l.Company 
into g 
select new InvoiceCompany() 
{ 
    Company = g.Key, 
    InvoiceValue = g.Sum() 
};