使用LinqToExcel进行子选择

时间:2012-02-04 15:37:08

标签: c# linq linq-to-excel

我正在试图弄清楚如何使用Linq执行子选择。我有一张带有“借记”和“信用”栏的excel表。我需要过滤掉任何具有借方列值(> 0.00)的行,这些行与进一步向下的信用列值匹配。两行必须具有相同的付款人ID。这是我到目前为止所提出的:

    public void balanceSheet()
    {
        foreach (Payment payment in this.payments)
        {
            // c[6] is the payers ID.
            var debits = from c in this.test.WorksheetNoHeader()
                         where c[6] != "0" && c[13] != "0.00" 
                         select c;
            // Find any rows in the sheet that have the same payer id AND the debit 
            // amount from the query above in it's credit column.
            foreach(LinqToExcel.RowNoHeader debit in debits)
            {
                var credits = from c in this.test.WorksheetNoHeader()
                              where c[6] == debit[6] && c[15] == debit[13]
                              select c;

                // Do something awesome if it finds something.

            }
        }
    }

我希望有一种更优雅的解决方案,可以按照上面的标准选择excel行,而不是每次循环遍历它们。我认为无论如何我都不会使用LINQ来充分利用它。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

LinqToExcel不支持联接,但您可以将其转换为内存列表,然后执行联接

var credits = from credit in this.test.WorksheetNoHeader().ToList()
  join debit in this.test.WorksheetNoHeader().ToList() on credit[6] equals debit[6]
  where debit[13] != "0.00"
  where debit[13] == credit[15]
  select credit

答案 1 :(得分:1)

尝试加入:

var credits = from credit in this.test.WorksheetNoHeader()
  join debit in this.test.WorksheetNoHeader() on credit[6] equals debit[6]
  where debit[13] != "0.00"
  where debit[13] == credit[15]
  select credit

有关详细信息:http://msdn.microsoft.com/en-us/library/bb311040.aspx