1

我做了一些 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();
4

2 回答 2

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”。

于 2012-08-09T12:35:27.993 回答
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 将包含您连接在一起的所有过滤。

于 2012-08-09T12:37:12.483 回答