c# - 在 C# 中返回两个列表

标签 c# return

我已经对此进行了一段时间的研究,但仍然不确定如何实现以及从一个单独的方法返回两个列表的最佳方式是什么?

我知道有类似的问题浮出水面,但他们似乎在哪个是最好的方法上相互矛盾。 我只需要简单有效地解决我的问题。 提前致谢。

最佳答案

方法有很多。

  1. 返回列表的集合。除非您不知道列表的数量或者超过 2-3 个列表,否则这不是一个好的方法。

    public static IEnumerable<List<int>> Method2(int[] array, int number)
    {
        return new List<List<int>> { list1, list2 };
    }
    
  2. 创建一个具有列表属性的对象并返回它:

    public class YourType
    {
        public List<int> Prop1 { get; set; }
        public List<int> Prop2 { get; set; }
    }
    
    public static YourType Method2(int[] array, int number)
    {
        return new YourType { Prop1 = list1, Prop2 = list2 };
    }
    
  3. 返回两个列表的元组 - 如果使用 C# 7.0 元组

    public static (List<int>list1, List<int> list2) Method2(int[] array, int number) 
    {
        return (new List<int>(), new List<int>());
    }
    
    var (l1, l2) = Method2(arr,num);
    

    C# 7.0 之前的元组:

    public static Tuple<List<int>, List<int>> Method2(int[] array, int number)
    {
        return Tuple.Create(list1, list2); 
    }
    //usage
    var tuple = Method2(arr,num);
    var firstList = tuple.Item1;
    var secondList = tuple.Item2;
    

我会选择选项 2 或 3,具体取决于编码风格以及此代码在更大范围内的适用范围。在 C# 7.0 之前,我可能会推荐选项 2。

关于c# - 在 C# 中返回两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43470715/

相关文章:

c - 从 C 函数返回数组

php - 选项卡在页面返回时错误地刷新

Java程序反转一个数字并判断它是否是回文

ruby - 我如何在 ruby​​ 中返回一段代码

c# - 是否有类似于 System.Console 的可嵌入到 WinForms 应用程序中的 .NET 类?

c# - WPF 边框属性无法正常工作

c# - 如何将参数传递给在 JQuery dialog() Open 事件上调用的操作

c# - 声明一个带有两个泛型参数的方法

使用模板化类型的 C# 模式匹配

带有增量的 Java return 语句 - 一般行为是什么?