Linq Queries Using C# – Code Snippet & Examples

Here I will explain you how Linq Query works in C#. You can replace your existing long code with one line of Linq query.

For using Linq in the C#.Net, you have to use System.Linq namespace.

using System.Linq;

Here I am explaining Linq with simple example:  

This is the simple

 var allDepartmentNames = new List();

  foreach (var department in employees.Department)
  {
      allDepartmentNames.Add(department.Name);
  }

 Now Convert this into LINQ-expression:

 
var allDepartmentNames = employees.Department.Select(x => x.Name).ToList();

 

How to get Duplicate Items from a List using Linq Query?

We have a list of Students class objects when we want to know the duplicate students name from this list using Ling query.

 
 var repeatedName = StudentsList.GroupBy(x => x.Name)
                                .SelectMany(g => g.Skip(1))
                                .Select(x => x.Name)
                                .Distinct().ToList();

Another Way:

 
var duplicates = lst.GroupBy(x => x).SelectMany(g => g.Skip(1));

Next Way:

 
var duplicates = lst.GroupBy(x => x)
                    .Where(g => g.Count() > 1)
                    .Select(g => g.Key)
                    .ToList();

Skip empty values for selecting duplicate values:

 
var duplicates = list.GroupBy(x => x).Where(x => !string.IsNullOrEmpty(x.Key)).SelectMany(g => g.Skip(1)).Distinct();

 

Get Duplicate values from the combination of two List?

 
var CityPinCode = new List();

var StudentsName= new List();

var pairs = StudentsName.Select((t, i) => new Tuple(StudentsName[i], CityPinCode[i])).ToList();

var duplicatesValues = pairs.GroupBy(i => new { i.Item1, i.Item2 }).Where(g => g.Count() > 1).Select(g => g.Key);

Condition based Linq Query:

I want to get the list of all the students who belongs to IT departments.

 
var itStudents = Students.Where(x=> Departments.Contains("IT")).ToList();

 

Get Index of the Nth Occurrence of a given char in a string:

If you want to know the index of any character occoring at particular occurrence in any string then you can use this below method.

This returns the index of the Nth occurrence of a given char in a string.

 

private static int GetIndexOfNthChar(string str, char ch, int occurrence)
{
var result = str.Select((c, i) => new { c, i })
                .Where(x => x.c == ch)
                .Skip(occurrence - 1)
                .FirstOrDefault();

return result != null ? result.i : -1;
}

Written by 

Leave a Reply

Your email address will not be published. Required fields are marked *