在C#中返回两个列表 [英] Returning two lists in C#
问题描述
我已经对此进行了一段时间的研究,但仍不确定如何实现以及从单独方法返回两个列表的最佳方法是什么?
I have been researching this for a while now, and am still unsure on how to implement and what is the best way to return two lists from a separate method?
我知道周围也有类似的问题,但是它们似乎彼此矛盾,因为哪种才是最好的方法。
我只需要简单有效的解决方案即可解决我的问题。
预先感谢。
I know there are similar question floating around but they seem to contradict each other as to which is the best way to do this. I just need simple and effective resolution to my problem. Thanks in advance.
推荐答案
有很多方法。
-
返回列表的集合。除非您不知道列表数量或列表数量超过2-3,否则这不是一个好方法。
Return a collection of the lists. This isn't a nice way of doing it unless you don't know the amount of lists or if it is more than 2-3 lists.
public static IEnumerable<List<int>> Method2(int[] array, int number)
{
return new List<List<int>> { list1, list2 };
}
创建一个具有列表属性的对象并返回: / p>
Create an object with properties for the list and return it:
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 };
}
返回两个列表的元组-使用$时特别方便b $ b C#7.0元组
Return a tuple of two lists - Especially convenient if working with C# 7.0 tuples
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之前的版本:
Tuples prior to 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。
I'd go for options 2 or 3 depending on the coding style and where this code fits in the bigger scope. Before C# 7.0 I'd probably recommend on option 2.
这篇关于在C#中返回两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!