嗨朋友我有一个对象列表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; }
}
请让我知道如何获得结果
答案 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>();
}
}