在C#中返回两个列表

我一直在研究这个问题,我仍然不确定如何实现以及从单独的方法返回两个列表的最佳方法是什么?

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

有很多方法。

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

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

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

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

    C#7.0之前的元组:

     public static Tuple, List> 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。

方法1

 public static void Method2(int[] array, out List list1, out List list2, int number) { list1= new List(); list2= new List(); ... } 

方法2

 public static Tuple, List> Method2(int[] array, int number) { list1= new List(); list2= new List(); ... return Tuple.Create(list1, list2) } 

方法3

创建一个具有2个道具list1,列表2,返回该类或只返回列表数组的类

最后在C#7上你可以做到

 public static (List list1, List list2) Method2(int[] array, int number) { ... return (list1, list2) } 

如果您使用的是更高版本的.NET和C#,那么只需使用元组(您可能需要安装包“System.ValueTuple”)

 public static void Method1() { int[] array1 = { }; int number1 = 1; (List listA, List listB) = Method2(array1, number1); } public static (List, List) Method2(int[] array, int number) { List list1 = new List(); List list2 = new List(); return (list1, list2); //<--This is where i need to return the second list } 

您可以查看将返回结构化为二维数组 。 这基本上是一个列表列表,可以显示为图形,其中每个“坐标”包含一个值。

下面是一个创建二维数组的示例,向point [0,2]添加一个值,然后从该点获取其值并将其写入屏幕:

 double[,] myNumbers = new double[4, 3]; myNumbers[0, 2] = 21.2; Console.WriteLine(myNumbers[0,2]); 

产量: 21.2

您应该将所需的列表作为对调用函数的引用传递。 例如

 public static void Method1() { List listA, listB; Method2(array1, number1, ref listA, ref listB); } public static void Method2(int[] array, int number, ref List listA, ref List listB) { //...do stuff here listA.Add(array[value]); listB.Add(array[value]); } 

更好的做法IMO会将两个列表传递给您想要的方法,并在方法本身内初始化/分配它们。 例:

 public static void Method2(int[] arr, List list1, List list2) { list1 = arr.OfType().ToList(); list2 = arr.OfType().ToList(); }