Reputation: 111
Hi Friends i have a list of objects private static List<Transaction> transactions;
i am querying through the list to filter the data with some criteria. but i am not able to return the list string. i am getting the error
Unable to cast object of type <>f__AnonymousType1`6[System.Int32,System.String,System.String,System.String,System.String,System.String] to type 'System.String'.
my plan is to make the datagridview source this list like 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;
}
my class file is
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; }
}
Please give me idea to get the result
Upvotes: 0
Views: 1901
Reputation: 21568
You don't need to convert to a string in order to use this result as a datasource (although if you actually need a string I can show you how to create a formatted string instead of an anonymous class object). You likely need something like this:
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>();
}
}
Upvotes: 1
Reputation: 149618
There is no need to project the entire collection onto an Anonymous Object
.
All you're actually doing is filtering by 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;
}
Upvotes: 3