[英]How can I return different DataTypes in lambda expression?
I want to obtain the following functionality. 我想获得以下功能。 But since I have to return different datatypes, the method isn't allowed.
但是由于我必须返回不同的数据类型,因此不允许使用该方法。 What will I do in this context?
在这种情况下我该怎么办?
.OrderBy(X =>
{
switch (OrderByColumn)
{
case "":
return X.a.CreatedOn;
case "BookCategoryName":
return X.a.BookCategoryName;
case "BookCategoryDescription":
return X.a.BookCategoryDescription;
}
return X.a.CreatedOn;
});
Or any other suggestion to get this functionality? 或任何其他建议来获得此功能?
I suggest you to change your logic to build query instead of making such logic in lambda: 我建议您更改逻辑以构建查询,而不要在lambda中进行这样的逻辑:
build query before like: 建立像之前的查询:
var query = list.Where(...);
if(OrderByColumn=="BookCategoryName")
{
query = query.OrderBy(x=>x.a.BookCategoryName);
}
....
at the end: 在末尾:
var result = query.ToList(); //for e.g.
it will work as you want and look much cleaner 它会根据您的需要工作并且看起来更干净
For each data type that your current lambda might return, use a separate block to define the ordering, and for any options that don't use that return type, return a constant. 对于您当前的lambda可能返回的每种数据类型,请使用单独的块定义顺序,对于不使用该返回类型的所有选项,请返回一个常量。
Guessing, for the moment, that CreatedOn
is a DateTime
and BookCategoryName
and BookCategoryDescription
are strings, it would be something like: 暂时猜测,
CreatedOn
是一个DateTime
而BookCategoryName
和BookCategoryDescription
是字符串,它类似于:
.OrderBy(X =>
{
switch (OrderByColumn)
{
case "":
return X.a.CreatedOn;
case "BookCategoryName":
return new DateTime(1900,1,1);
case "BookCategoryDescription":
return new DateTime(1900,1,1);
}
return X.a.CreatedOn;
})
.ThenBy(X =>
{
switch (OrderByColumn)
{
case "":
return "";
case "BookCategoryName":
return X.a.BookCategoryName;
case "BookCategoryDescription":
return X.a.BookCategoryDescription;
}
return "";
});
(Of course, the constant values could be moved out to be real constants or variables, etc, but I wanted to make the above snippet self contained) (当然,常量值可以移出为实常数或变量等,但是我想使上面的代码片段完全包含在内)
,Another option is to extract the ordering field selection itself to a separate method, like this: ,另一个选择是将排序字段选择本身提取到一个单独的方法中,如下所示:
public IEnumerable<Data> SelectData(IEnumerable<Data> data, Func<Data, bool> predicate)
{
return data
.Where(predicate)
.OrderBy(GetCurrentOrderingField);
}
private IComparable GetCurrentOrderingField(Data x)
{
switch (OrderByColumn)
{
case "BookCategoryName":
return x.a.BookCategoryName;
case "BookCategoryDescription":
return x.a.BookCategoryDescription;
}
return x.a.CreatedOn;
}
This, of course, for fields implementing IComparable interface. 当然,这适用于实现IComparable接口的字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.