在C#中返回两个列表
发布时间:2020-12-15 18:28:53 所属栏目:百科 来源:网络整理
导读:我一直在研究这个问题,我仍然不确定如何实现以及从单独的方法返回两个列表的最佳方法是什么? 我知道有类似的问题浮出水面,但它们似乎互相矛盾,哪个是最好的方法. 我只需要简单有效地解决我的问题. 提前致谢. 解决方法 有很多方法. 返回列表的集合.这不是一
我一直在研究这个问题,我仍然不确定如何实现以及从单独的方法返回两个列表的最佳方法是什么?
我知道有类似的问题浮出水面,但它们似乎互相矛盾,哪个是最好的方法. 解决方法
有很多方法.
>返回列表的集合.这不是一个很好的方法,除非你不知道列表的数量或它是否超过2-3个列表. public static IEnumerable<List<int>> Method2(int[] array,int number) { return new List<List<int>> { list1,list2 }; } >创建一个包含列表属性的对象并将其返回: 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 }; } >返回两个列表的元组 – 如果使用,特别方便 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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |