LINQ C# - How do we get specific column (startswith) of a row in a datatable using LINQ C#

  • Thread starter Thread starter Gani tpt
  • Start date Start date
G

Gani tpt

Guest
I have datatable and i want to get only particular column startswith "Material" and get a only that rows.

Normally we can get row and filter. here is a challenge to filter particular specific columns and get rows using LINQ C#.

sample code below.

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Material1", typeof(string)));
dt.Columns.Add(new DataColumn("Material2", typeof(string)));
dt.Columns.Add(new DataColumn("Material3", typeof(string)));
dt.Columns.Add(new DataColumn("Quantity1", typeof(string)));
dt.Columns.Add(new DataColumn("Quantity2", typeof(string)));
dt.Columns.Add(new DataColumn("Quantity3", typeof(string)));
dt.Columns.Add(new DataColumn("Quantity4", typeof(string)));
dt.Columns.Add(new DataColumn("Quantity5", typeof(string)));
dt.Columns.Add(new DataColumn("Manfcomp1", typeof(string)));
dt.Columns.Add(new DataColumn("Manfcomp2", typeof(string)));
dt.Columns.Add(new DataColumn("Manfcomp3", typeof(string)));
dt.Columns.Add(new DataColumn("Manfcomp4", typeof(string)));

dt.Rows.Add(new object[] { "A1", "", "A3", "100", "200", "", "", "500", "Rolt", "", "nedo", "" });
//dt.Rows.Add(new object[] { "B1", "B2", "", "", "2100", "3000", "340", "", "", "Mary", "", "Eclip" });
//dt.Rows.Add(new object[] { "", "C2", "C3", "800", "", "", "", "300", "binu", "Manilp", "jucy", "" });
//dt.Rows.Add(new object[] { "D1", "", "", "", "4000", "", "5000", "10", "Zinko", "Lame", "", "" });


string matvalue = null;
string Finalvalue = null;

var QryIn1 = (from r in dt.AsEnumerable()
select new
{
// To get Max value of Material1 ....to....Material..X
Matvalue = dt.Columns.Cast<DataColumn>().
Where(c => c.ColumnName.StartsWith("Material"))
.Select( c => r.Field<string>( c.Ordinal ))
}).Distinct();

foreach (var n in QryIn1)
{

matvalue = Convert.ToString(n.Matvalue); // not getting the values.
//Finally concatenate all the material values
Finalvalue = string.Join("", matvalue);
}

String output = Finalvalue; // output result should come as "A1A3" -


Output result not coming the value as "A1A3"...?

What is the problem in above code..?

Continue reading...
 
Back
Top