Vincent Dagpin
Vincent Dagpin

Reputation: 3611

Selecting DataRow using Linq in c#

How can I make this to shorter one using Linq?

int id = 0;
foreach (DataRow dr in tableClientTableAdapter1.GetData())
{
     if (dr[0].ToString() == txtClientName.Text)
      {
          id = Convert.ToInt16(dr[1]);
          break;
      }
}

I tried using this

var a = tableClientTableAdapter1.GetData().Cast<DataRow>().Where(cName => cName[0].ToString() == txtClientName.Text);
MessageBox.Show(a[1].ToString());

But I got this error:

Error 1 Cannot apply indexing with [] to an expression of type 'System.Data.EnumerableRowCollection' C:\Users\[email protected]\Desktop[Final][GlobalTek] Monitoring System[GlobalTek] Monitoring System\xfrmProjectAwarding.cs 89 37 [GlobalTek] Monitoring System

Any help!!

Upvotes: 3

Views: 13134

Answers (3)

Gary.S
Gary.S

Reputation: 7131

If you are going to use the cast method you should also use the field method.

var a = tableClientTableAdapter1.GetData().Cast<DataRow>().Where(t => t.Field<string>(0) == txtClientName.Text).ToList();

ToList() added if you want to access via index

If you only need the first match you can replace where with First/FirstOrDefault depending on how you want null handled

var a = tableClientTableAdapter1.GetData().Cast<DataRow>().First(t => t.Field<string>(0) == txtClientName.Text);

Upvotes: 2

Anthony Pegram
Anthony Pegram

Reputation: 126932

var a = is a sequence of DataRow items that you are trying to treat as a single object. If you desire one result, use one of

.First()
.FirstOrDefault()
.Single()
.SingleOrDefault()

on the query, with the difference being your expectation for the result. If more than one item can be present but you're only interested in the first of them, go with First(). If only one item should match and it's an error if there are more, go with Single(). If, in either scenario, it's possible for there to be no matches, use the appropriate *OrDefault() version.

var row = tableClientTableAdapter1.GetData().
               Cast<DataRow>()
               .Where(cName => cName[0].ToString() == txtClientName.Text)
               .FirstOrDefault(); 

if (row != null)
{
     // extract value
}

Upvotes: 7

Joel Coehoorn
Joel Coehoorn

Reputation: 416049

Try this:

var a = Convert.ToInt16(tableClientTableAdapter1.GetData().Cast<DataRow>().First(r => r[0].ToString() == txtClientName.Text)[1]);

But be warned it will throw an exception if there is no match. If that's a possibility, you should do this:

var a = tableClientTableAdapter1.GetData().Cast<DataRow>().FirstOrDefault(r => r[0].ToString() == txtClientName.Text);
var b = (a != null)?Convert.ToInt16(a[1]):0;

Upvotes: 2

Related Questions