Free Web Development Online Tutorials, Learn to Code
Learn LINQ with C#, Method Syntax LINQ Example with C#

LINQ Method Syntax C# Example

Now we learn LINQ method syntax (some people call as fluent syntax)
Method syntax is combination of extension methods and Lambda expression

Method Syntax in LINQ

First we create a student list object with some data, so we can use that for all examples in this tutorials

var studentsStream = new List<Student> { 
    new Student { FullName = "Aruna", StreamId=1,  Score = 10 },
    new Student { FullName = "Janet", StreamId=2,  Score = 9  },
    new Student { FullName = "Ajay", StreamId=1,  Score = 11 },
    new Student { FullName = "Kunal", StreamId=2,  Score = 13  },
    new Student { FullName = "Chandra", StreamId=2,  Score = 8  },
};

Example 1: from above student list we want to select only student names

LINQ Method syntax with lambda select one column
//Method syntax
var _studentNames1 = studentsStream.Select(s => s.FullName);

Example 2: from above student list select students where score is more than 10
LINQ method syntax using extension method (where ) and lambda in list
Here you can notice how query syntax is difference than method syntax.

// Way 1 (Query syntax) var studentList = from stu in studentsStream
where stu.Score>10 select stu;
// Way 2: Using Lambda Expression var studentList1 = studentsStream.Where<Student>(stu => stu.Score> 10);

method syntax in linq

Now if you check the Where extension method, you will see that Where method accepts a predicate as Func.

public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) 
Comment
Name
Email
Website
Subscribe
 
Learn LINQ .Net

LINQ Method Syntax Example with C#

linq Interview Questions Answers

LINQ C# examples | Join Asp.net MVC Course