LINQ:我如何缩短代码?

时间:2012-08-09 12:32:06

标签: c# linq predicate

我做了一些LINQ,它运行得很好,但我不喜欢这种类型的编码,我想缩短它,但不太确定如何。

有谁知道如何缩短这部分代码?我之前听说过谓词,但不太确定如何实现它们?

 List<Voucher> list = new List<Voucher>();    

if (String.IsNullOrEmpty(Search.SearchText) && Search.Status == 0)
{
    list = (from voucherslist in db.Vouchers
            //where voucherslist.Status != (int)VoucherStatus.Removed
            select voucherslist)                              
            .Take(100)
            .ToList();
}

if (!String.IsNullOrEmpty(Search.SearchText) && Search.Status ==0)
{
    list = (from voucherslist in db.Vouchers
            where voucherslist.Title.Contains(Search.SearchText)                                
            select voucherslist).Take(100).ToList();
}

if (String.IsNullOrEmpty(Search.SearchText) && Search.Status > 0)
{
    list = (from voucherslist in db.Vouchers
            where voucherslist.Status == Search.Status                                    
            select voucherslist).Take(100).ToList();
}

if (!String.IsNullOrEmpty(Search.SearchText) && Search.Status > 0)
{
    list = (from voucherslist in db.Vouchers
            where voucherslist.Status == Search.Status
            && voucherslist.Title.Contains(Search.SearchText)  
            select voucherslist).Take(100).ToList();
} 

// Convert
ret = VouchersConverter.Convert(list);

// Get Business Details
foreach (ENT_Voucher item in ret)
    item.BusinessDetails = this._businessesBLL.GetBusinessDataByID(item.BusinessID);

// Refine and sort
ret = ret.Where(x=>x.BusinessDetails.Accept == true)
            .OrderByDescending(x => x.Status.Equals(1))
            .ThenByDescending(x => x.StartDate).ToList();

2 个答案:

答案 0 :(得分:4)

您当前的逻辑看起来有些不合适,但我怀疑您想要:

var query = db.Vouchers;
if (...)
{       
   query = query.Where(v => v.Title.Contains(Search.SearchText);
}
if (...)
{       
   query = query.Where(v => v.Status == Search.Status);
}
// etc

List<Voucher> list = query.Take(100).ToList();    

Where使用多次调用会在所有过滤器上有效地应用“AND”。

答案 1 :(得分:4)

要删除重复,请先设置列表。

list = (from voucherslist in db.Vouchers
        //where voucherslist.Status != (int)VoucherStatus.Removed
        select voucherslist);

然后在需要时添加标题搜索:

if (!String.IsNullOrEmpty(Search.SearchText))
{
    list = list.Where(x => x.Title.Contains(Search.SearchText));
} 

状态搜索:

if (Search.Status > 0)
{
    list = list.Where(x => x.Status == Search.Status);
}

最后,拿走你的100并将其压平到列表中。

list = list.Take(100).ToList();

要记住的是,在.ToList()调用之前,这实际上不会构造和执行SQL查询,并且将要执行的SQL将包含您连接在一起的所有过滤。