Return the only value from list, the type's default value if empty, or call the errorAction for 2 or more. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:List

Description

Return the only value from list, the type's default value if empty, or call the errorAction for 2 or more.

Demo Code

// Copyright (c) Microsoft Corporation.  All rights reserved.
using System.Linq;
using System.Diagnostics.Contracts;
using System.Collections.ObjectModel;

public class Main{
        /// <summary>
        /// Return the only value from list, the type's default value if empty, or call the errorAction for 2 or more.
        /// </summary>
        public static T SingleDefaultOrError<T, TArg1>(this IList<T> list, Action<TArg1> errorAction, TArg1 errorArg1)
        {/*  w w w. j  a  v  a2s.co m*/
            Contract.Assert(list != null);
            Contract.Assert(errorAction != null);

            switch (list.Count)
            {
                case 0:
                    return default(T);

                case 1:
                    T value = list[0];
                    return value;

                default:
                    errorAction(errorArg1);
                    return default(T);
            }
        }
}

Related Tutorials