Returns a single value in list matching type TMatch if there is only one, null if there are none of type TMatch or calls the errorAction with errorArg1 if there is more than one. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:List

Description

Returns a single value in list matching type TMatch if there is only one, null if there are none of type TMatch or calls the errorAction with errorArg1 if there is more than one.

Demo Code

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

public class Main{
        /// <summary>
        /// Returns a single value in list matching type TMatch if there is only one, null if there are none of type TMatch or calls the
        /// errorAction with errorArg1 if there is more than one.
        /// </summary>
        public static TMatch SingleOfTypeDefaultOrError<TInput, TMatch, TArg1>(this IList<TInput> list, Action<TArg1> errorAction, TArg1 errorArg1) where TMatch : class
        {/*  w  w  w .ja  va2 s. c om*/
            Contract.Assert(list != null);
            Contract.Assert(errorAction != null);

            TMatch result = null;
            for (int i = 0; i < list.Count; i++)
            {
                TMatch typedValue = list[i] as TMatch;
                if (typedValue != null)
                {
                    if (result == null)
                    {
                        result = typedValue;
                    }
                    else
                    {
                        errorAction(errorArg1);
                        return null;
                    }
                }
            }
            return result;
        }
}

Related Tutorials