Tuesday, May 22, 2012

How to use LINQ to return one columns values (C#, LINQ)

I wanted to find a way to get all the data from one column in one pass.  I could do this with a loop or I can use LINQ to shorten my code.
To show the difference I will show you the manual loop way and the LINQ way.

DataTable ldtDataTable = new DataTable("Data");
ldtDataTable.Columns.Add("Column1", typeof(String));
ldtDataTable.Columns.Add("Column2", typeof(String));
ldtDataTable.Columns.Add("Column3", typeof(String));
ldtDataTable.Rows.Add(new object[] { "Row1Column1", "Row1Column2", "Row1Column2" });
ldtDataTable.Rows.Add(new object[] { "Row2Column1", "Row2Column2", "Row2Column2" });
ldtDataTable.Rows.Add(new object[] { "Row3Column1", "Row3Column2", "Row3Column2" });
ldtDataTable.Rows.Add(new object[] { "Row4Column1", "Row4Column2", "Row4Column2" });
ldtDataTable.Rows.Add(new object[] { "Row5Column1", "Row5Column2", "Row5Column2" });

/// I ONLY WANT TO GET THE VALUES IN Column2, separated with a ; (semi-colon)
///This is the variable that will hold my columns values
string lstrValues = string.Empty;
///Here is the manual loop
foreach(DataRow dr in ldtDataTable.Rows)
{
     lstrValues += Convert.ToString(dr["Column2"]) +"; ";
}
Console.WriteLine(lstrValues);
The output from the above code is:
Row1Column2; Row2Column2; Row3Column2; Row4Column2; Row5Column2; 
All though this is completely acceptable, there is a way to do this with out the loop. I am using the same DataTable as outlined as above as well as the same variable
Here is the LINQ way
var t = (from value in ldtDataTable.AsEnumerable() select value.Field("Column2"));
Array.ForEach((String[])t.ToArray(), z => lstrValues += z + "; ");
The output from the above code is:
Row1Column2; Row2Column2; Row3Column2; Row4Column2; Row5Column2;
As you can see this is a much cleaner and simpler way to get the same data.
If you wanted to shorten your code even more, you can do the following:
Array.ForEach((String[])(from value in ldtDataTable.AsEnumerable() select value.Field("Column2"))
.ToArray(), z => lstrValues += z + "; ");

No comments:

Post a Comment