adopilot adopilot - 1 month ago 19
C# Question

Linq way to find value in DataTable

May I ask someone to help me write this in LINQ,

DataTable dt = new DataTable();

DataColumn dcValue = new DataColumn();
dcValue.ColumnName = "value";

DataColumn dvDisplay = new DataColumn();
dvDisplay.ColumnName = "display";

DataColumn dvIsDefualt = new DataColumn();
dvIsDefualt.ColumnName = "isDefalt";

dt.Columns.Add(dcValue,int);
dt.Columns.Add(dvDisplay,string);
dt.Columns.Add(dvIsDefualt,bool);

this.tipRacuna.DataSource = ds.Tables[0];
this.tipRacuna.ValueMember = "value";
this.tipRacuna.DisplayMember = "display";

this.tipRacuna.SelectedValue = findDefault(dt);//linq to find first value with default = true;


}
private int findDefault(DataTable dtt)
{
int i= 0;

foreach (DataRow dr in dtt.Rows)
{
if (bool.Parse(dr["isDefalt"].ToString()))
{
return int.Parse(dr["value"].ToString());
}
}
return i;
}


As I am getting more involved in C# and programming at all, I am getting more intersting in LINQ queries.

In begins I always skip LINQ taking argument as I know TSQL no needs for another Query language, but when I see how many lines of code i can save using LINQ i start learning it.

Answer

Assuming that your DB columns are strongly-typed (best):

dtt.AsEnumerable().Where( dr => dr.Field<bool>("isDefault" ) )
    .Select( dr => dr.Field<int>( "value" ) ).FirstOrDefault();

With type conversion:

dtt.AsEnumerable().Where( dr => Convert.ToBoolean( dr["isDefault"] ) )
    .Select( dr => Convert.ToInt32( dr["value"] ) ).FirstOrDefault();

With parsing:

dtt.AsEnumerable().Where( dr => bool.Parse( dr["isDefault"].ToString() ) )
    .Select( dr => int.Parse( dr["value"].ToString() ) ).FirstOrDefault();

Note that I have corrected the spelling of "isDefalt" to "isDefault".