gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:44:56 24 4
gpt4 key购买 nike

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

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

最佳答案

方法有很多。

  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/

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