链多个WHERE子句

时间:2018-05-08 20:41:12

标签: asp.net-mvc entity-framework linq

根据条件,我尝试将多个WHERE子句链接到TransactionDataList变量。请告知正确的方法。

我收到此错误:

  

错误CS0266无法隐式转换类型' System.Collections.Generic.IEnumerable'到' System.Collections.Generic.List'。   存在显式转换(您是否错过了演员?)

代码:

List<Transaction> QueriedTransactionList;
QueriedTransactionList = db.Transactions.ToList();

List<TransactionViewModel> TransactionDataList = QueriedTransactionList.Select(x => new TransactionViewModel
{
    TTransactionID = x.TTransactionID,
    BatchID = x.BatchID,
    TransactionDateTime = x.TransactionDateTime,
    TransactionStatus = x.TransactionStatus,
    TaxPayerName = x.Card.TaxPayer.TaxPayerName,
    TaxPayerEmail = x.Card.TaxPayer.TaxPayerEmail
}).GroupBy(x => x.BatchID).Select(x => x.LastOrDefault()).OrderByDescending(x => x.TTransactionID).ToList();

if (Request.QueryString["Port"] != "")
{
    int Port = Convert.ToInt32(Request.QueryString["Port"]);
    TransactionDataList = TransactionDataList.Where(x => x.Card.PortID == Port);
}

if (Request.QueryString["Status"] != "")
{
    string Status = Request.QueryString["Status"];
    TransactionDataList = TransactionDataList.Where(x => x.TransactionStatus == Status);
}

if (Request.QueryString["TIN"] != "")
{
    string TIN = Request.QueryString["TIN"];
    TransactionDataList = TransactionDataList.Where(x => x.Card.TaxPayerTIN == TIN);
}

1 个答案:

答案 0 :(得分:5)

List<T>IEnumerable<T>,但IEnunumerable<T>无法保证成为列表。 SelectWhere的返回类型为IEnumerable<T>,无法分配给TransactionDataList

更改

List<TransactionViewModel> TransactionDataList = QueriedTransactionList.Select...

IEnumerable<TransactionViewModel> TransactionDataList = QueriedTransactionList.Select...

错误将消失。如果您想要访问IList<T>提供的方法,则需要使用ToList扩展方法转换回列表。