在 C# 中返回两个列表

Returning two lists in C#(在 C# 中返回两个列表)

本文介绍了在 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.

推荐答案

有很多方法.

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

  1. 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 };
}

  • 创建一个具有列表属性的对象并返回它:

  • 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 };
    }
    

  • 返回一个包含两个列表的元组 - 使用时特别方便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# 中返回两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

    本文标题为:在 C# 中返回两个列表

    基础教程推荐