我有两个清单。两个列表的类型都继承自相同的基类型。我想迭代它们并执行仅使用基类功能的操作,而不必依次使用两个基本相同的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;
}
答案 0 :(得分:6)
这应该可以解决问题......
foreach (var item in list1.Concat<Base>(list2))
{
// Do your thing
}
编辑:我将Union
更改为Concat
因为我认为它可能更合适。
答案 1 :(得分:0)
只需使用基类,如下所示:
List<Babby> list = new List<Base>();
list.AddRange(returnBabby1());
list.AddRange(returnBabby2());
foreach (Base item in list)
item.var = 50;
sendBabby1(list.OfType<Babby1>().ToList());
sendBabby2(list.OfType<Babby2>().ToList());
(当然这假设你有在基类中声明的变量)
答案 2 :(得分:0)
如果您打算简单地迭代列表而不是在列表中添加项目或执行其他操作,则可以使用IEnumerable<T>
static SendBaby(IEnumerable<Base> list)
{
...
}
...
SendBaby(list1)
SendBaby(list2)
来实现此目的:
{{1}}
答案 3 :(得分:0)
您可以使用for Count
代替for循环。 (如果比较确实消耗了额外的CPU周期。)
for(int i=0;i<baby1.Count||i<baby2.Count;i++)
{
if(baby1.Count<i)
baby1[i].field = 50;
if(baby2.Count<i)
baby2[i].field = 50;
}
答案 4 :(得分:0)
这很好:
var babies1 = new List<Baby1>(5);
for (int i = 0; i < 5; i++)
{
babies1.Add(new Baby1 { Name = "Babies1 " + i, Var1 = 1});
}
var babies2 = new List<Baby2>(5);
for (int i = 0; i < 5; i++)
{
babies2.Add(new Baby2 { Name = "Babies2 " + i });
}
foreach (Baby b in babies1.Union<Baby>(babies2))
{
b.Var1 = 50;
}
foreach (var baby2 in babies2)
{
Console.WriteLine(baby2.Var1);
}
foreach (var baby1 in babies1)
{
Console.WriteLine(baby1.Var1);
}