LINQ Single()方法

LINQ Single()方法 首页 / LinQ入门教程 / LINQ Single()方法

In LINQ, the Single() method is used to return the single element from the collection, which satisfies the condition. In case, if the Single() method found more than one element in collection or no element in the collection, then it will throw the "InvalidOperationException" error.

LINQ Single()方法的语法

使用LINQ Single()方法从集合中获取单个元素的语法。

int a = objList.Single();

在上面的语法中,我们使用LINQ Single()方法从列表中获取单个元素。

LINQ Single()方法示例

以下是LINQ Single()方法从集合中获取单个元素的示例。

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

namespace ConsoleApp1
{
    class Programme2
    {
        static void Main(string[] args)
        {
//create an object objStudent of the class Student added the record to the list.
            List objStudent = new List()
            {
                new Student() { Name = "Shubham Rastogi", Gender = "Male",Location="Chennai" },
                new Student() { Name = "Rohini Tyagi", Gender = "Female", Location="Chennai" },
                new Student() { Name = "Praveen Alavala", Gender = "Male",Location="Bangalore" },
                new Student() { Name = "Sateesh Rastogi", Gender = "Male", Location ="Vizag"},
                new Student() { Name = "Madhav Sai", Gender = "Male", Location="Nagpur"}
            };
    //initialize the array objList
                int[] objList = { 1 };
    //objStudent.Single() used to select the student
                var user = objStudent.Single(s => s.Name == "Shubham Rastogi");
                string result = user.Name;
                int val = objList.Single();
                Console.WriteLine("Element from objStudent: {0}", result);
                Console.WriteLine("Element from objList: {0}", val);
                Console.ReadLine();
        }
    }
        class Student
        {
           public string Name { get; set; }
           public string Gender { get; set; }
           public string Location { get; set; }
        }
}

From the above example, we are getting the single element from the collection "objStudent" using the LINQ Single() operator.

输出:

LINQ Single() Method




祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Service Mesh实战 -〔马若飞〕

手机摄影 -〔@随你们去〕

代码之丑 -〔郑晔〕

恋爱必修课 -〔李一帆〕

说透区块链 -〔自游〕

大厂设计进阶实战课 -〔小乔〕

深入浅出可观测性 -〔翁一磊〕

技术领导力实战笔记 2022 -〔TGO 鲲鹏会〕

结构思考力 · 透过结构看表达 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)