c# - 遍历两个继承类(相同基类)的两个列表

标签 c#

我有两个列表。两个列表的类型都继承自相同的基类型。我想遍历它们并执行仅使用基类功能的操作,而无需一个接一个地使用两个基本相同的 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;
}

最佳答案

这应该可以解决问题...

foreach (var item in list1.Concat<Base>(list2))
{
    // Do your thing
}

编辑:我将 Union 更改为 Concat,因为我认为它可能更合适。

关于c# - 遍历两个继承类(相同基类)的两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8428849/

相关文章:

c# - 当 "Class not registered"时,实例化 COM 组件失败并显示 "Run As Administrator"

c# - CsvHelper 并并行查询大型 csv 文件

c# - ASP.NET - 如何在页面中写入一些 html?使用 Response.Write?

c# - 如何在 FFmpeg.AutoGen 中设置 ffmpeg 命令行选项

c# - 如果文件夹为空,则使用 C# 删除文件夹

c# - 在 DrawText Wpf C# 中使用自定义字体

c# - 通用构造函数和继承

c# - 删除过多的 try-catch block

c# - 抽象和继承有什么区别?

c# - 如何在没有 HTML 标签的情况下从数据库中获取数据?