📜  LINQ到列表/集合

📅  最后修改于: 2021-01-06 05:55:14             🧑  作者: Mango

LINQ到列表/集合

LINQ到列表/集合意味着在列表或集合上编写LINQ查询。通过对集合或列表使用LINQ查询,我们可以用最少的编码来过滤,排序或删除重复项。

LINQ到列表或集合的语法

这是在列表或集合上编写LINQ查询以获取所需元素的语法。

var result = from e in objEmp

select new

{

   Name = e.Name,

  Location = e.Location

};

在以上语法中,我们编写了LINQ查询,以从“ objEmp ”集合/列表对象中获取所需的数据。

LINQ到列表/集合的示例

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Programme2
    {
        static void Main(string[] args)
        {
//create object objEmp of class Employee and create a list of the Employee information
           List objEmp = new List
    ()
    {
    new Employee { EmpId=1,Name = "Akshay", Location="Chennai" },
    new Employee { EmpId=2,Name = "Vaishali", Location="Chennai" },
    new Employee { EmpId=3,Name = "Priyanka", Location="Guntur" },
    new Employee { EmpId=4,Name = "Preeti", Location ="Vizag"},
    };
    //here use the LINQ query to sort or select the element from the collection of data
    var result = from e in objEmp
    where e.Location.Equals("Chennai")
    select new
    {
    Name = e.Name,
    Location = e.Location
    };
    //foreach loop is used to print the value of the 'result' having the output of the LINQ query
    foreach (var item in result)
    {
    Console.WriteLine(item.Name + "\t | " + item.Location);
    }
    Console.ReadLine();
    }

    }
    //create class employee
    class Employee
    {
    public int EmpId { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    }
    }

在上面的代码中,我们在列表“ objEmp ”上使用了LINQ查询,以根据需求获取所需的元素。

输出: