博客
关于我
LINQ之Single,SingleOrDefault
阅读量:315 次
发布时间:2019-03-04

本文共 6179 字,大约阅读时间需要 20 分钟。

目录

Single()

Single()的用法是获取唯一的元素。

public static TSource Single<TSource>( this IEnumerable<TSource> source );
听起来可能有点抽象,请继续往下看。

代码示例:

public static class Program{       static void Main( string[] args )    {           int[] numbers = new int[] {    5 };        int result  = numbers.Single();        System.Console.WriteLine( "数据:{0}", numbers.Text() );        System.Console.WriteLine( "结果:{0}", result );        System.Console.ReadKey();    }    public static string Text
( this IEnumerable
i_source ) { string text = string.Empty; foreach( var value in i_source ) { text += string.Format( "[{0}], ", value ); } return text; }} 数据:[5],结果:5

通过single()我们获取了数组中唯一的5元素。

不止如此,我们还可以指定获取的条件。

示例代码:

public static class Program{       static void Main( string[] args )    {           int[] numbers = new int[] {    1, 2, 3, 5, 7, 11 };        // 大于10的值        int result  = numbers.Single( value => value > 10 );        System.Console.WriteLine( "数据:{0}", numbers.Text() );        System.Console.WriteLine( "结果:{0}", result );        System.Console.ReadKey();    }    public static string Text
( this IEnumerable
i_source ) { string text = string.Empty; foreach( var value in i_source ) { text += string.Format( "[{0}], ", value ); } return text; }} 数据:[1], [2], [3], [5], [7], [11],结果:11

Single()可以处理任何类型。

因此,无论是float,还是string,它都能处理任何事情。
以下是使用class的数组的示例。

示例代码:

public static class Program{       private class Parameter    {           public int      ID      {    get; set; }        public string   Name    {    get; set; }        public override string ToString()        {               return string.Format( "ID:{0}, Name:{1}", ID, Name );        }    }    static void Main( string[] args )    {           Parameter[] parameters = new Parameter[]        {               new Parameter() {    ID =  5, Name = "正一郎" },            new Parameter() {    ID = 13, Name = "清次郎" },            new Parameter() {    ID = 25, Name = "誠三郎" },            new Parameter() {    ID = 42, Name = "征史郎" },        };        // ID小于10        Parameter result  = parameters.Single( value => value.ID < 10 );        System.Console.WriteLine( "数据:{0}", parameters.Text() );        System.Console.WriteLine( "结果:{0}", result );        System.Console.ReadKey();    }    public static string Text
( this IEnumerable
i_source ) { string text = string.Empty; foreach( var value in i_source ) { text += string.Format( "[{0}], ", value ); } return text; }} 数据:[ID:5, Name:正一郎], [ID:13, Name:清次郎], [ID:25, Name:誠三郎], [ID:42, Name:征史郎],结果:ID:5, Name:正一郎

但是,在以下情况使用Single()会报错。

1.序列包含多个元素。(直接使用Single())System.InvalidOperationException:序列包含多个元素
2.序列包含多个匹配元素。(有指定条件的情况)System.InvalidOperationException:序列包含多个匹配元素
3.序列为空。System.InvalidOperationException:序列不包含任何元素
4.没有元素满足条件。System.InvalidOperationException:序列不包含匹配的元素

SingleOrDefault()

SingleOrDefault()Single()用法相同,但是在未返回任何元素的情况下会返回该类型的默认值。

public static TSource SingleOrDefault<TSource>( this IEnumerable<TSource> source );

public static TSource SingleOrDefault<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate );

代码示例:

public static class Program{       static void Main( string[] args )    {           int[] numbers = new int[] {    };        int result = 0;        try        {               result = numbers.SingleOrDefault();        }        catch( System.Exception i_exception )        {               System.Console.WriteLine( "异常:{0}", i_exception );            System.Console.ReadKey();            return;        }                System.Console.WriteLine( "数据:{0}", numbers.Text() );        System.Console.WriteLine( "结果:{0}", result );        System.Console.ReadKey();    }    public static string Text
( this IEnumerable
i_source ) { string text = string.Empty; foreach( var value in i_source ) { text += string.Format( "[{0}], ", value ); } return text; }}数据:结果:0

那么我们加上条件呢?

代码示例:

public static class Program{       static void Main( string[] args )    {           int[] numbers = new int[] {    1, 2, 3, 5, 7, 11 };        int result = 0;        try        {               // 大于20            result = numbers.SingleOrDefault( value => value > 20 );        }        catch( System.Exception i_exception )        {               System.Console.WriteLine( "异常:{0}", i_exception );            System.Console.ReadKey();            return;        }          System.Console.WriteLine( "数据:{0}", numbers.Text() );        System.Console.WriteLine( "结果:{0}", result );        System.Console.ReadKey();    }    public static string Text
( this IEnumerable
i_source ) { string text = string.Empty; foreach( var value in i_source ) { text += string.Format( "[{0}], ", value ); } return text; }} 数据:[1], [2], [3], [5], [7], [11],结果:0

但是,使用SingleOrDefault()要小心,因为可能会无法区分“找不到元素,则返回默认值0”还是“找到元素0,所以我返回了它。

还要注意一点的是,如果获取到多个元素,则会引发异常

代码示例:

public static class Program{       static void Main( string[] args )    {           int[] numbers = new int[] {    1, 2, 3, 5, 7, 11 };        int result = 0;        try        {               // 获取奇数            result = numbers.SingleOrDefault( value => value % 2 == 1 );        }        catch( System.Exception i_exception )        {               System.Console.WriteLine( "异常:{0}", i_exception );            System.Console.ReadKey();            return;        }          System.Console.WriteLine( "数据:{0}", numbers.Text() );        System.Console.WriteLine( "结果:{0}", result );        System.Console.ReadKey();    }    public static string Text
( this IEnumerable
i_source ) { string text = string.Empty; foreach( var value in i_source ) { text += string.Format( "[{0}], ", value ); } return text; }} 异常:System.InvalidOperation Exception:序列中包含多个匹配的元素已完成

所以,Single()SingleOrDefault()是用来获取唯一元素的!

不应在获取多个元素情况下使用它!

转载地址:http://ffnq.baihongyu.com/

你可能感兴趣的文章
Netty WebSocket客户端
查看>>
netty 主要组件+黏包半包+rpc框架+源码透析
查看>>
Vue过渡 & 动画---vue工作笔记0014
查看>>
Netty 异步任务调度与异步线程池
查看>>
Netty 的 Handler 链调用机制
查看>>
Netty 编解码器和 Handler 调用机制
查看>>
Netty 编解码器详解
查看>>
Netty 解决TCP粘包/半包使用
查看>>
Netty 调用,效率这么低还用啥?
查看>>
Netty 高性能架构设计
查看>>
Netty+Protostuff实现单机压测秒级接收35万个对象实践经验分享
查看>>
Netty+SpringBoot+FastDFS+Html5实现聊天App详解(一)
查看>>
netty--helloword程序
查看>>
netty2---服务端和客户端
查看>>
【Flink】Flink 2023 Flink易用性和稳定性在Shopee的优化-视频笔记
查看>>
Netty5.x 和3.x、4.x的区别及注意事项(官方翻译)
查看>>
netty——bytebuf的创建、内存分配与池化、组成、扩容规则、写入读取、内存回收、零拷贝
查看>>
netty——Channl的常用方法、ChannelFuture、CloseFuture
查看>>
netty——EventLoop概念、处理普通任务定时任务、处理io事件、EventLoopGroup
查看>>
netty——Future和Promise的使用 线程间的通信
查看>>