본문 바로가기

Test Code/C#

[Linq] DataTable에서 Linq 사용하기 Select

using System;
using System.Linq;
using System.Data;

class Test_Linq
{
	static void Main()
	{
		DataTable table = new DataTable();
		table.Columns.Add("lot");
		table.Columns.Add("data",typeof(double));
		
		table.Rows.Add("A", 45.2);
		table.Rows.Add("A", 45.8);
		table.Rows.Add("A", 45.9);
		table.Rows.Add("B", 45.1);
		table.Rows.Add("B", 45.5);
		
		table.AcceptChanges();
		
		// SELECT 
		var query = 
			from 	dr in table.AsEnumerable()
			where 	dr.Field<string>("lot")== "A" && 
					dr.Field<double>("data")>=45.5
			select new 
			{	
				lot = dr.Field<string>("lot"),
				data = dr.Field<double>("data")
			};
		
		// DISPLAY
		Console.WriteLine("**. Select 결과");
		Console.WriteLine("Lot\tData");
		foreach(var x in query)
		{
			Console.WriteLine("{0}\t{1}", x.lot, x.data);
		}
	}	
}