如何将列表对象转换为列表字符串(获取错误无法转换类型的对象)

时间:2014-11-02 14:46:34

标签: c# .net linq

嗨朋友我有一个对象列表private static List<Transaction> transactions;

我正在查询列表以使用某些条件过滤数据。但我无法返回列表字符串。我收到了错误

  

无法投射类型的对象   &LT;&GT; f__AnonymousType1`6 [System.Int32,System.String,System.String,System.String,System.String,System.String]   输入&#39; System.String&#39;。

我的计划是将datagridview源设为此列表,如dataGridView2.DataSource = BasicClass.banksearch("ABC");

public static List<string> banksearch(string bankname, string sdate = null, string edate = null, string condition = null)
    {
        List<string> returnstr = new List<string>();
        if (sdate == null && edate == null)//only bank
        {
            returnstr = transactions
                .Where(t => t.BankName == bankname)
                .Select(t => new
                 {
                     TransactionID = t.TransactionID,
                     BankName = t.BankName,
                     TemplateModel = t.TemplateModel,
                     Date = t.Date.ToString(),
                     PayeeName = t.PayeeName,
                     Amount = t.Amount.ToString()
                 }).Cast<String>().ToList();
        }
       return returnstr;
       }

我的班级文件是

class Transaction
{
        public int TransactionID { get; set; }
        public string BankName { get; set; }
        public string TemplateModel { get; set; }
        public DateTime Date { get; set; }
        public string PayeeName { get; set; }
        public decimal Amount { get; set; }        
}

请让我知道如何获得结果

2 个答案:

答案 0 :(得分:3)

无需将整个集合投射到Anonymous Object上。 您实际所做的只是按bankname过滤:

public static List<Transaction> BankSearch(string bankname, string sdate = null, string edate = null, string condition = null)
{
    List<Transaction> filteredTransactions = new List<Transaction>();
    if (sdate == null && edate == null)
    {
        filteredTransactions = transactions.Where(t => t.BankName == bankname).ToList();
    }

    return filteredTransactions;
}

答案 1 :(得分:1)

您不需要转换为字符串,以便将此结果用作数据源(尽管如果您确实需要一个字符串,我可以向您展示如何创建格式化字符串而不是匿名类对象)。你可能需要这样的东西:

public static List<Transaction> banksearch(string bankname, string sdate = null, string edate = null, string condition = null)
    {
        if (sdate == null && edate == null)//only bank
        {
           return transactions // type: List<Transaction>
                .Where(t => t.BankName == bankname)
                .ToList();
        } else {
           return new List<Transaction>();
       }
  }