在我的程序中我正在阅读excel表并正在做一些linq选择,这工作正常。
问题:我尝试通过应用If语句进行预选。变量将在每种情况下分配(if / else),但编译器没有看到。编译器告诉我初始化var beforehands,但是当我尝试这个时,我失败了,因为我只习惯像sting,int或double之类的变量,我可以在之前轻松分配:
//This function takes the downloaded xlsx and makes selection of applicable items
var excel = new ExcelQueryFactory("list.xlsx");
//get all items with discount
if (onlyAcceptDiscountedItems == true)
{
var discounts = from s in excel.Worksheet()
where s["Discount/Premium"].Cast<string>().StartsWith("-")
select s;
}
else
{
var discounts = excel.Worksheet();
}
if (discounts.Count() != 0)
{
//some application logic comes here
}
当我尝试这样做时:
var excel = new ExcelQueryFactory("list.xlsx");ter code here
var discounts = excel.Worksheet();
if (onlyAcceptDiscountedItems == true)
{
discounts = from s in excel.Worksheet()
where s["Discount/Premium"].Cast<string>().StartsWith("-")
select s;
}
if (discounts.Count() != 0)
{
//some application logic comes here
}
我在第二个codenippet的第5行收到以下错误:
错误CS0266无法隐式转换类型 'System.Linq.IQueryable'来 'LinqToExcel.Query.ExcelQueryable'。一个明确的 存在转换(你错过了演员吗?)
答案 0 :(得分:7)
我看到了三个选项,尽管还有其他选项:
您可以显式声明所需的变量类型,在这种情况下,您可以在每种情况下单独初始化它:
IQueryable<LinqToExcel.Row> discounts;
if (onlyAcceptDiscountedItems == true)
{
discounts = from s in excel.Worksheet()
where s["Discount/Premium"].Cast<string>().StartsWith("-")
select s;
}
else
{
discounts = excel.Worksheet();
}
您可以使用条件运算符初始化变量:
var discounts = onlyAcceptDiscountedItems
? excel.Worksheet().Where(s => s["Discount/Premium"].Cast<string>().StartsWith("-"))
: excel.Worksheet();
您可以在两个地方删除调用excel.Worksheet
的冗余:
IQueryable<LinqToExcel.Row> discounts = excel.Worksheet();
if (onlyAcceptDiscountedItems)
{
discounts = discounts.Where(s => s["Discount/Premium"].Cast<string>().StartsWith("-"));
}
此外,您可能希望使用discounts.Any()
代替discounts.Count() > 0
,因为您并不真正关心计数。