我一直在研究这个问题,我仍然不确定如何实现以及从单独的方法返回两个列表的最佳方法是什么?
我知道有类似的问题浮出水面,但它们似乎互相矛盾,哪个是最好的方法.我只需要简单有效地解决我的问题.提前致谢.
Gil*_*een 20
有很多方法.
返回列表的集合.这不是一个很好的方法,除非你不知道列表的数量或它是否超过2-3个列表.
public static IEnumerable<List<int>> Method2(int[] array, int number)
{
return new List<List<int>> { list1, list2 };
}
Run Code Online (Sandbox Code Playgroud)创建一个包含列表属性的对象并将其返回:
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 };
}
Run Code Online (Sandbox Code Playgroud)返回两个列表的元组 - 如果使用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);
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)我会选择2或3选项,具体取决于编码风格以及此代码在更大范围内的适用范围.在C#7.0之前,我可能会建议选项2.
| 归档时间: |
|
| 查看次数: |
16762 次 |
| 最近记录: |