Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to return two lists in C#?

I am almost embarrassed to ask this question, but as a long time C programmer I feel that perhaps I am not aware of the best way to do this in C#.

I have a member function that I need to return two lists of a custom type (List<MyType>) and I know beforehand that I will always have a return value of only two of these lists.

The obvious options are :

public List<List<MyType>> ReturnTwoLists();

or

public void ReturnTwoLists(ref List<MyType> listOne, ref List<myType> listTwo);

Both seem to be non-optimal.

Any suggestions on how to improve this?

The first way doesn't make it clear in the syntax that only 2 lists are being returned, and the second uses references rather then a return value, which seem so non-c#.

like image 622
Jeremy White Avatar asked Jul 08 '09 16:07

Jeremy White


People also ask

Can we return two list in C#?

You cannot return two items using the return keyword. The easiest thing for you to do is pass these list instances as parameters to the method. Then assign them here and you will have them available in the calling method.


2 Answers

First of all, that should probably be out, not ref.

Second, you can declare and return a type containing the two lists.

Third, you can declare a generic Tuple and return an instance of that:

class Tuple<T,U> {
   public Tuple(T first, U second) { 
       First = first;
       Second = second;
   }
   public T First { get; private set; }
   public U Second { get; private set; }
}

static class Tuple {
   // The following method is declared to take advantage of
   // compiler type inference features and let us not specify
   // the type parameters manually.
   public static Tuple<T,U> Create<T,U>(T first, U second) {
        return new Tuple<T,U>(first, second);
   }
}

return Tuple.Create(firstList, secondList);

You can extend this idea for different number of items.

like image 63
mmx Avatar answered Sep 29 '22 08:09

mmx


Return this:

public class MyTwoLists {
    public List<MyType> ListOne {get;set;}
    public List<MyType> ListTwo {get;set;}
}
like image 44
John Saunders Avatar answered Sep 29 '22 09:09

John Saunders