我有两个清单.两个列表的类型都继承自相同的基类型.我想迭代它们并执行仅使用基类功能的操作,而不必依次使用两个基本相同的foreach循环.
我无法将列表复制到另一个列表或类似的东西,因为我需要在操作完成后单独使用原始表单中的列表.
有没有办法在不编写函数的情况下执行此操作?
class Program
{
static void Main(string[] args)
{
// I have two lists of inherited classes
List<Babby1> list1 = returnBabby1();
List<Babby2> list2 = returnBabby2();
// I want to iterate through both, and do the same thing, which is a part
// of the base class functionality.
// Basically I want this to be a single foreach loop.
foreach (Babby1 item in list1)
item.var = 50;
foreach (Babby2 item in list2)
item.var = 50;
// I have to send them as separate lists, the type being the original (inherited) class
sendBabby1(list1);
sendBabby2(list2);
}
static void sendBabby1(List<Babby1> list)
{
}
static void sendBabby2(List<Babby2> list)
{
}
static List<Babby1> returnBabby1()
{
return new List<Babby1>();
}
static List<Babby2> returnBabby2()
{
return new List<Babby2>();
}
}
class Base
{
public int var;
}
class Babby1 : Base
{
public int var1;
}
class Babby2 : Base
{
public int var2;
}
Run Code Online (Sandbox Code Playgroud)
这应该是诀窍......
foreach (var item in list1.Concat<Base>(list2))
{
// Do your thing
}
Run Code Online (Sandbox Code Playgroud)
编辑:我改为Union,Concat因为我认为它可能更合适.
| 归档时间: |
|
| 查看次数: |
702 次 |
| 最近记录: |