将通用列表转换为另一个通用列表的方法

man*_*noj -1 .net c# generics list

我有数据输入List<One>并希望转换为List<Two>.我的代码是

 public static List<T> ListCopy<T>(List<T> input)
    {
        List<T> mylist = new List<T>();
        //Logic Goes here 
        return mylist;
    }
Run Code Online (Sandbox Code Playgroud)

从这只过程数据List<One>List<One> ,但我想从加工List<One>List<Two> 喜欢

    List<One> l = new List<One>();
    List<Two> t = new List<Two>();
    t = ListConvert<Two>(l);
Run Code Online (Sandbox Code Playgroud)

我能为此做些什么?

Mar*_*zek 6

您可以使用LINQ来完成它,但是您仍然需要提供一个应该用于转换元素的函数:

public static List<TResult> ListCopy<TSource, TResult>(List<TSource> input, Func<TSource, TResult> convertFunction)
{
    return input.Select(x => convertFunction(x)).ToList();
}
Run Code Online (Sandbox Code Playgroud)

和样品用法(简单的铸造作为转换功能)

var t = ListConvert(l, x => (Two)x);
Run Code Online (Sandbox Code Playgroud)