How to ask “Is there exactly one element satisfying condition” in LINQ?

后端 未结 4 949
庸人自扰
庸人自扰 2021-01-01 14:40

Quick question, what\'s the preferable way to programmaticaly ask \"Is there exactly one element in this sequence that satisfies X condition?\" using Linq?

i.e.

4条回答
  •  被撕碎了的回忆
    2021-01-01 14:52

    Once I had the issue to determine if exactly one item is contained I decided to create following extension. In my optionion it fits good into the set of already existing extensions (e.g.: SingleOrDefualt, FirstOrDefault ...).

     public static class IEnumerableExtension
    {
        public static TProject OneOrDefault(this IEnumerable sequence, Func projection)
        {
            var enumerator = sequence.GetEnumerator();
            bool firstMoveNext = enumerator.MoveNext();
            TInput current = enumerator.Current;
            if (firstMoveNext && !enumerator.MoveNext())
            {
                return projection(current);
            }
            else
            {
                return default;
            }
        }
    }
    

提交回复
热议问题