Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

return - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are many ways.

  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 };
    }
    
  2. 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 };
    }
    
  3. 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);
    

    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;
    

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...