-1

As a novice in C#, I'm trying to read each row from a datable. Then depending of the value from a special column, I will use that value into a switch.

Here the portion of the code that is bothering me :

foreach(DataRow row in dtTableList.Rows)
{

   string selection = (from DataRow line in dtTableList.Rows select (string)line["Name"]);

   switch(selection)
   { 
      //The switch case statement
   }

The line with "string selection" is apparently wrong, I get as an error message :

"Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string'"

I tried replacing string selection by var selection but then I can't use it in my switch.

Do any of you know what could possibly be the cause of my error and how to solve it ?

For information, I tried to apply the code from another post on StackOverflow.

Community
  • 1
  • 1
Karaelfte
  • 143
  • 1
  • 12
  • `line["Name"]` is an IEnumerable. Try `line["Name"].FirstOrDefault()` to get the first element. – Nicklas Andersen Sep 27 '16 at 12:12
  • You must use Enumerate the expression, in this case with `FirstOrDefault()` for example. – Halis S. Sep 27 '16 at 12:13
  • You already have `row`, use `row["Name"]` in switch. – Sinatr Sep 27 '16 at 12:13
  • The `foreach` and the `from` will both go through all of the `dtTableList`, is that really what you want/need? – H H Sep 27 '16 at 12:14
  • Thank you for your answers, Nicklas and hellowstone, but when I try to add the FirstOrDefault, it is said that "It's impossible to convert a group of methods to type 'String'" Henk, I need to do a selection for each row in my datable, so I though it was the best solution to do so. – Karaelfte Sep 27 '16 at 12:18
  • 1
    @Nicklas, Never mind my previous comment, just forgot to add "()" at the end. – Karaelfte Sep 27 '16 at 13:03

2 Answers2

4

A DataTable normally stores multiple rows, so result is an IEnumerable<string> not a single string. If you're only interested in the first row or it contains only one:

string selection = dtTableList.AsEnumerable()
    .Select(r => r.Field<string>("Name"))
    .FirstOrDefault();
// selection == null --> not a single row at all;

If you are already in the foreach-loop you don't need the LINQ query at all:

foreach(DataRow row in dtTableList.Rows)
{
    string selection = row.Field<string>("Name");
    switch(selection) 
    {
       // ...
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • As I said later in the comment above your answer, I need to do a selection for all the rows in my datatable. So I though I needed to write it like that, do I need to change it to fit what you propose or do you think I should keep it ? – Karaelfte Sep 27 '16 at 12:23
0

You can Use like below code

string selection = dtTableList.AsEnumerable().Select(dr => dr.Field<string>("CoumnName").ToString()).FirstOrDefault();
Bharat
  • 2,441
  • 3
  • 24
  • 36