添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Converts an array of any type to List passing a mapping delegate Func that returns type T. If T is null, it will not be added to the collection. If the array is null, then a new instance of List() is returned.

Source

public static List<T> ToList<T>(this Array items, Func<object, T> mapFunction)
    if (items == null || mapFunction == null)
        return new List<T>();            
    List<T> coll = new List<T>();
    for (int i = 0; i < items.Length; i++)
        T val = mapFunction(items.GetValue(i));
        if(val != null)
            coll.Add(val);
    return coll;
    

Example

--> Make another extension method
public static List<T> ToList<T>(this object[] items)
            return items.ToList<T>(o => { return (T)o; });
Reduces this : http://extensionmethod.net/Details.aspx?ID=351
To this:
public static List<T> EnumToList<T>() where T : struct
            return Enum.GetValues(typeof(T)).ToList<T>(enumVal => { return (T)Enum.Parse(typeof(T), enumVal.ToString()); });
--> Use in Linq
var myItems = from i in array.ToList<MyType>( o => { return (MyType)o; }) select i;

Author: James Levingston

Submitted on: 19 okt. 2010

Language: C#

Type: System.Array

Views: 11183

ExtensionMethod.NET was built by Loek van den Ouweland and Fons Sonnemans with ASP.NET Core, HTML, CSS, Javascript, SQL Server and some of the great methods you have posted here. By using this website, you agree to the legal stuff. We thank all who contributed to this website for the last twelve years. It really helped making this website a success! Looking for Visual Studio Code Snippets? Visit our sister site VisualStudioCodeSnippets.com.