返回lambda表达式</t>中的List <t>中的所有内容

时间:2013-10-02 11:01:40

标签: c# .net linq lambda

我在LINQ中使用lambda表达式,当条件满足时我必须得到所有结果,否则它应该过滤。

//代码

 List<Dispatch> objDispatch = (List<Dispatch>)Session["Data"];
objDispatch = objDispatch.FindAll(dispatch => dispatch.CustomerTransName == ddlTransporterName.SelectedItem.Text && dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date && dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date);

在上面的代码中,我在第一个条件中使用某些条件过滤结果集,我需要帮助。

如果传输者名称为“ALL”,则应返回与Date条件匹配的所有结果集,否则应根据TransporterName返回。

我怎样才能实现这个目标?

5 个答案:

答案 0 :(得分:2)

string name = ddlTransporterName.SelectedItem.Text;
objDispatch = objDispatch.FindAll(dispatch => 
   (name == "ALL" || dispatch.CustomerTransName == name) 
   && dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date 
   && dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date);

如果运输商名称为“ALL”,则名称OR条件将提供true,并且不会检查CustomerTransName

答案 1 :(得分:2)

纯逻辑。

if(ddlTransporterName.SelectedItem.Text == "ALL") {
  //return all
} else {
  //Do your filter logic
}

或者,重复性较少的代码:

objDispatch = objDispatch.FindAll(
  dispatch => (ddlTransporterName.SelectedItem.Text == "ALL" || dispatch.CustomerTransName == ddlTransporterName.SelectedItem.Text) 
  && dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date 
  && dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date);

答案 2 :(得分:2)

如果您希望这是LINQ,那么您需要实际使用LINQ方法,例如使用Where。此外,如果您的日期转换不是特定于行,则应该在外面进行日期转换,否则它们将每次转换。不仅如此,它还使代码更具可读性......

var selectedTransporter = ddlTransporterName.SelectedItem.Text;
var fromDate = Convert.ToDateTime(FromDate).Date;
var toDate = Convert.ToDateTime(ToDate).Date;
var query = objDispatch.Where(x => (selectedTransporter == "All" || x.CustomerTransName == selectedTransporter) && x.InvoiceDate.Date >= fromDate && x.InvoiceDate.Date <= toDate);

答案 3 :(得分:0)

我认为这应该足够了:

List<Dispatch> objDispatch = (List<Dispatch>)Session["Data"];

List<Dispatch> filteredDispatches = objDispatch.Where(dispatch => dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date && dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date).ToList();

if (ddlTransporterName.SelectedItem.Text != "ALL")
{
    filteredDispatches = filteredDispatches.Where(dispatch => dispatch.CustomerTransName == ddlTransporterName.SelectedItem.Text).ToList();
}

答案 4 :(得分:0)

我认为这样的事情应该有效:

List<Dispatch> objDispatch = (List<Dispatch>)Session["Data"];

var _fromDate = Convert.ToDateTime(FromDate);
var _toDate = Convert.ToDateTime(ToDate);

objDispatch = objDispatch
    .FindAll(dispatch => Selector(
         dispatch, ddlTransporterName.SelectedItem.Text, _fromDate, _toDate));

static bool Selector(
    Dispatch dispatch, string name, DateTime fromDate, DateTime toDate)
{
    if (dispatch.CustomerTransName == "ALL")
    {
        return dispatch.InvoiceDate.Date >= fromDate.Date
            && dispatch.InvoiceDate.Date <= toDate.Date;
    }

    return dispatch.CustomerTransName == name;
}