谓词未在LinqToExcel查询中应用

时间:2014-12-09 20:12:45

标签: c# linq-to-excel

我遇到了LinqToExcel图书馆并且一直在玩它。我似乎误解了查询是如何工作的。我创建了一个包含一些客户信息的简单工作表。使用LinqPad,我设置了我的查询:

void Main()
{
    string path = @"E:\Documents\LINQPad\LINQPad Queries\LinqToExcel\Customers.xlsx";

    var excel = new ExcelQueryFactory(path);

    // Mappings and Transforms:
    excel.AddMapping<Customer>(c => c.Contact, "Contact Person");
    excel.AddMapping<Customer>(c => c.CompanyName, "Company Name");
    excel.AddMapping<Customer>(c => c.IsPreferred, "Preferred");
    excel.AddTransformation<Customer>(c => c.IsPreferred, cellValue => cellValue == "Yes");

    // Query:
    var preferrdCompanies = from c in excel.Worksheet<Customer>("Customers")
                            where c.IsPreferred  // this has no effect?
                            orderby c.CompanyName
                            select new { c.CompanyName, c.Contact, c.IsPreferred };

    // Display:
    preferrdCompanies.Dump("Preferred Customers:");
}

// Define other methods and classes here
class Customer
{
    public string Contact { get; set; }
    public string CompanyName { get; set; }
    public bool IsPreferred { get; set; }   
}

由于某种原因,谓词未被应用。从“是”文本转换为 true (bool)正在运行。如果我写:

preferrdCompanies.ToList().Where(c => c.IsPreferred).Dump("Preferred Customers:");

我按照您的预期获得过滤后的列表。我一直在寻找我的代码中的一个简单的错误,但它没有抛出任何异常,我找不到任何明显的错误,所以我想我只是不明白查询功能如何?

任何答案/解释都将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:0)

您可以尝试在where子句中明确设置c.IsPreferred == true,看看是否能解决您的问题。

var preferrdCompanies = from c in excel.Worksheet<Customer>("Customers")
                        where c.IsPreferred == true
                        orderby c.CompanyName
                        select new { c.CompanyName, c.Contact, c.IsPreferred };