Reputation: 23830
Okay now this below is working
List<string> lstKnownMoves = dsAttacksTemp.Tables[0].Rows.
Cast<DataRow>().Select(r => r["Column1"].ToString()).ToList();
But i want to make it work like below and not working
List<string> lstKnownMoves = dsAttacksTemp.Tables[0].Rows.
Cast<DataRow>().Select(r => r["Column1"].ToString(),r => r["Column2"].ToString(),r => r["Column3"].ToString()).ToList();
So instead of 1 dataset datarow column, i want to add multiple columns into the list. How can i do that ?
Upvotes: 3
Views: 11320
Reputation: 42497
Well, assuming you want to be able to access each column individually, you'd want to return an array of strings.
List<string[]> lstKnownMoves = dsAttacksTemp.Tables[0].Rows
.Cast<DataRow>().Select(r => new[]
{
r["Column1"].ToString(),
r["Column2"].ToString(),
r["Column3"].ToString()
}).ToList();
Then for each row, you can get the string value of a column by index:
foreach(var item in lstKnownMoves)
Console.WriteLine("Column1: {0} Column2: {1} Column3: {2}", item);
If you want basically a map of columns, and would rather not create a class to act as a tuple as in the selected answer, you can use List<dynamic>
:
List<dynamic> lstKnownMoves = dsAttacksTemp.Tables[0].Rows
.Cast<DataRow>().Select(r => new
{
Column1 = r["Column1"].ToString(),
Column2 = r["Column2"].ToString(),
Column3 = r["Column3"].ToString()
}).ToList<dynamic>();
foreach(var item in lstKnownMoves)
Console.WriteLine("Column1: {0} Column2: {1} Column3: {2}",
item.Column1, item.Column2, item.Column3);
Upvotes: 1
Reputation: 30892
You could use SelectMany if you just to dump the contents of the fields into a list.
List<string> lstKnownMoves = dsAttacksTemp.Tables[0].Rows
.Cast<DataRow>()
.SelectMany(r => new string[]{
r["Column1"].ToString(),
r["Column2"].ToString(),
r["Column3"].ToString()})
.ToList();
If however, you want to extract the fields into another object, you could do something like:
class KnownMove {
public string Column1 {get; set;}
public string Column2 {get; set;}
public string Column3 {get; set;}
}
List<KnownMove > lstKnownMoves = dsAttacksTemp.Tables[0].Rows
.Cast<DataRow>()
.SelectMany(r => new KnownMove{
Column1 = r["Column1"].ToString(),
Column2 = r["Column2"].ToString(),
Column3 = r["Column3"].ToString()})
.ToList();
Upvotes: 4
Reputation: 26922
I assume you want a list of an object with several string properties instead of a list of string arrays.
List<object> lstKnownMoves = dsAttacksTemp.Tables[0].Rows.
Cast<DataRow>().Select(r => new {
Col1 = r["Column1"].ToString(),
Col2 = r["Column2"].ToString(),
Col3 = r["Column3"].ToString()
}).ToList();
This way you'd get a List<T>
where T
is an anonymous object with 3 string properties, namely Col1
, Col2
and Col3
. I guess this is what you are asking for.
Upvotes: 1