SingleOrDefault() throws an exception on more than one element

后端 未结 7 1917
野性不改
野性不改 2021-02-05 12:17

I\'m getting an exception whenever I fetch like this

Feature f = o.Features.SingleOrDefault(e => e.LinkName == PageLink);

because this can r

7条回答
  •  星月不相逢
    2021-02-05 12:25

    Alternatively, if you only want the item when there is exactly one match and do not want to throw when there are more than one, this can be easily accomplished. I've created an extension method for this in my project:

    public static class QueryableExtensions
    {
        public static TSource SingleWhenOnly(this IQueryable source)
        {
            if (source == null)
                throw new ArgumentNullException("source");
    
            var results = source.Take(2).ToArray();
    
            return results.Length == 1 ? results[0] : default(TSource);
        }
    
        public static TSource SingleWhenOnly(this IQueryable source, Expression> predicate)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (predicate == null)
                throw new ArgumentNullException("predicate");
    
            var results = source.Where(predicate).Take(2).ToArray();
    
            return results.Length == 1 ? results[0] : default(TSource);
        }
    }
    

提交回复
热议问题