Asdfg
Asdfg

Reputation: 12213

get data from DataTable using LINQ

I have a datatable and i want to print the content of the table to console.

System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("FName");
dt.Columns.Add("LName");

DataRow dr;
dr = dt.NewRow();
dr["FName"] = "FName1";
dr["LName"] = "LName1";
dt.Rows.Add(dr);


dr = dt.NewRow();
dr["FName"] = "FName2";
dr["LName"] = "LName2";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["FName"] = "FName3";
dr["LName"] = "LName3";
dt.Rows.Add(dr);

I want output on console like this:

Row 1: FNAme = Fname1, LName = LName1
Row 2: FNAme = Fname2, LName = LName2
Row 2: FNAme = Fname3, LName = LName3

How can i do this using LINQ?

Upvotes: 0

Views: 22242

Answers (4)

Krypes
Krypes

Reputation: 561

This isn't really the purpose of LINQ but if you really want...

dt.Rows.Cast<DataRow>()
  .Select((DataRow dr, int i) =>
    {
      return String.Format("Row {0}: FNAme = {1}, LName = {2}", i, dr["FName"], dr["LName"]);
    })
  .All((line) =>
    {
      Console.WriteLine(line);
      return true;
    });

Upvotes: 4

SirViver
SirViver

Reputation: 2441

A more generic solution (also using some LINQ, since you seem to have the hots for it ;-))

DataTable dt = ...;

string formatStr = String.Join(", ", Enumerable.Range(0, dt.Columns.Count)
    .Select(c => dt.Columns[c].ColumnName + " = {" + c + "}").ToArray());

for (int i = 0; i < dt.Rows.Count; i++)
    Console.WriteLine("Row " + i + ": " + String.Format(formatStr, dt.Rows[i].ItemArray));

Upvotes: 1

msarchet
msarchet

Reputation: 15242

So you could use LINQ and write something like this

DataTable.Rows.ToList().ForEach(r => Console.WriteLine(String.Format("Row {0}: FNAme = {1}, LName = {2}", dr.Rows.IndexOf(r) + 1, r.Item["FName"], r.Item["LName"])

But for what you're doing a foreach loop makes more sense

//Borrowing Dustin Lanes foreach here.

StringBuilder sb = new StringBuilder();
foreach (DataRow dr in DataTable.Rows)
{
    sb.Append(String.Format("Row {0}: FNAme = {1}, LName = {2}", dt.Rows.IndexOf(row) + 1, dr["FName"], dr["LName"]));
}

The reason that I say that a foreach loop makes more sense is that it's clearer what you are doing. The implementation is simpler.

LINQ is great, but I try to only use it when it provides a clearer representation of what I am doing. It's honestly becoming the defacto answer for any thing to do with any code dealing with collections and sometimes it isn't the answer.

Upvotes: 3

Dustin Laine
Dustin Laine

Reputation: 38503

This has nothing to do with LINQ, you will need to iterate over the items.

StringBuilder sb = new StringBuilder();
foreach (DataRow dr in DataTable.Rows)
{
    sb.Append(String.Format("Row {0}: FNAme = {1}, LName = {2}", dt.Rows.IndexOf(row) + 1, dr["FName"], dr["LName"]));
}

Upvotes: 5

Related Questions