How to Use LINQ query on a DataTable in C#?


This content was proof-read by Grammarly. You can Try Grammary for FREE

Below is a sample code snippet that demonstrates the usage of the LINQ query on a DataTable in C#.

How to Use LINQ query on a DataTable in C#?

using System;

using System.Collections.Generic;

using System.Data;

using System.Linq;

namespace AbundantCode

{

internal class Program

{

//How to Use LINQ query on a DataTable in C# ?

private static void Main(string[] args)

{

List<CodeSnippet> CodeLst = new List<CodeSnippet>();

DataTable dt = new DataTable();

dt.Columns.Add("Name");

dt.Columns.Add("Code");

DataRow row1 = dt.NewRow();

row1["Name"] = "Abundantcode";

row1["Code"] = "1-1-1";

dt.Rows.Add(row1);

DataRow row2 = dt.NewRow();

row2["Name"] = "Plenty of sourcecode";

row2["Code"] = "1-1-12";

dt.Rows.Add(row2);

var results = (from m in dt.AsEnumerable()

where m.Field<string>("Code") == "1-1-12"

select m).FirstOrDefault();

Console.WriteLine(results["Name"]);

Console.ReadLine();

}

}

public class CodeSnippet

{

public string Name { get; set; }

public string Code { get; set; }

}

}
How to Use LINQ query on a DataTable in C#?
%d bloggers like this: