deepak.kumar.goyal
deepak.kumar.goyal

Reputation: 45

Is is possible to populate a datatable using a Lambda expression(C#3.0)

I have a datatable. I am populating some values into that. e.g.

DataTable dt =new DataTable();
dt.Columns.Add("Col1",typeof(int));
dt.Columns.Add("Col2",typeof(string));
dt.Columns.Add("Col3",typeof(DateTime));
dt.Columns.Add("Col4",typeof(bool));


for(int i=0;i< 10;i++)
dt.Rows.Add(i,"String"  + i.toString(),DateTime.Now,(i%2 == 0)?true:false);

There is nothing wrong in this program and gives me the expected output.

However, recently , I am learning Lambda and has done some basic knowledge.

With that I was trying to do the same thing as under

Enumerable.Range(0,9).Select(i = > 
{

    dt.Rows.Add(i,"String"  + i.toString(),DateTime.Now,(i%2 == 0)?true:false);
});

But I am unsuccessful.

Is my approach correct(Yes I know that I am getting compile time error; since not enough knowledge on the subject so far)?

Can we achieve this by the way I am doing is a big doubt(as I donot know.. just giving a shot).

If so , can some one please help me in this regard.

I am using C#3.0 and dotnet framework 3.5

Thanks

Upvotes: 3

Views: 1924

Answers (2)

Amy B
Amy B

Reputation: 110181

The Select method returns an enumerable with deferred execution. To make the enumerable execute, you must enumerate it. Also - dt.Rows.Add returns void, so it is an Action, not a Func and cannot be used in the Select call.

Instead of using Select, how about using

ToList<T>().ForEach<T>(Action<T>)

As in:

Enumerable.Range(0,9)
  .ToList()
  .ForEach(i =>  
  {
    dt.Rows.Add(i,"String"  + i.ToString(), DateTime.Now, (i%2 == 0) );
  });

Upvotes: 2

Anthony Faull
Anthony Faull

Reputation: 17987

You're very close. Just remove the {curly braces} and the space in "= >".

Enumerable.Range(0, 9).Select(i => dt.Rows.Add(i, 
    "String" + i.ToString(), DateTime.Now, (i%2 == 0) ? true : false));

Upvotes: 2

Related Questions