gpt4 book ai didi

c# - 不使用 LINQ 转换对象列表

转载 作者:行者123 更新时间:2023-11-30 19:48:12 24 4
gpt4 key购买 nike

来 self 在这里的问题:Cast in List object

我接受了使用 LINQ 的答案:

myA = myB.Cast<A>().ToList();

我有一个问题:我们有任何其他不使用 LINQ 的解决方案,因为我的应用程序使用的是 .NET Framework 2.0。

更新:如果我有几个派生自 myA 的类 myB、myC、myD、myE,... . The function input is a list<T> and the function output is a list<myA>.

谢谢。

最佳答案

一个简单的 foreach 就可以解决这个问题(为了便于阅读,我将类命名为 Foo 和 Bar)

myFoos = new List<Foo>();
foreach (Bar bar in myBars)
{
myFoos.Add((Foo)bar);
}

问题编辑后:

要将多个子类的列表转换为基类,我会创建一个名为 BaseCollection 的类,而不是从 List 继承,因为列表通常还需要一些其他操作。一些有用的方法可能是:

 public class BaseCollection : List<Base>
{
public static BaseCollection ToBase<T>(IEnumerable<T> source) where T: Base
{
BaseCollection result = new BaseCollection();
foreach (T item in source)
{
result.Add(item);
}
return result;
}

public static List<T> FromBase<T>(IEnumerable<Base> source) where T: Base
{
List<T> result = new List<T>();
foreach (Base item in source)
{
result.Add((T)item);
}
return result;
}


public static List<T> ChangeType<T, U>(List<U> source) where T: Base where U:Base
{
List<T> result = new List<T>();
foreach (U item in source)
{
//some error checking implied here
result.Add((T)(Base) item);
}
return result;
}

....
// some default printing
public void Print(){...}
....
// type aware printing
public static void Print<T>(IEnumerable<T> source) where T:Base {....}
....
}

这将使我能够轻松地将任何后代与基类集合相互转换,并像这样使用它们:

List<Child> children = new List<Child>();
children.Add(new Child { ID = 1, Name = "Tom" });
children.Add(new Child { ID = 2, Name = "Dick" });
children.Add(new Child { ID = 3, Name = "Harry" });

BaseCollection bases = BaseCollection.ToBase(children);
bases.Print();

List<Child> children2 = BaseCollection.FromBase<Child>(bases);
BaseCollection.Print(children2);

关于c# - 不使用 LINQ 转换对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5713535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com