Method Syntax An Query Syntax C#



Query syntax and method syntax are semantically identical, but many people find query syntax simpler and easier to read. Some queries must be expressed as method calls. For example, you must use a method call to express a query that retrieves the number of elements that match a specified condition.

using System;
using System.Linq;

namespace CSharpLINQ
{
    class SimpleQuery
    {
		static void Main( )
		{
			int[] numbers = { 2, 5, 28, 31, 17, 16, 42 };
			var numsQuery = from n in numbers where n < 20 select n; 	// Query syntax
			var numsMethod = numbers.Where(x => x < 20); 				// Method syntax
			
			int numsCount = (from n in numbers where n < 20 select n).Count();	// Combined

			foreach (var x in numsQuery)
				Console.Write("{0}, ", x);
			
			Console.WriteLine();
			
			foreach (var x in numsMethod)
				Console.Write("{0}, ", x);
		}
    }
}

0 Comment's

Comment Form

Submit Comment