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

前端 未结 5 2349
情话喂你
情话喂你 2020-12-31 05:12

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 fu

5条回答
  •  自闭症患者
    2020-12-31 05:39

    You have a few options:

    use a Pair if the lists are meaningless in order:

     public Pair,List ReturnTwoLists()
     {
            return new Pair(new List

    You can use out or ref parameters, as you mentioned. This is a good option if one list is more meaningful than the other.

    You could use a dictionary if the client will know the keys, or wants to do the work to look them up:

     public Dictionary ReturnTwoLists()
     {
            Dictionary> d = new Dictionary>();
            d.Add("FirstList",new List());
            d.Add("SecondList",new List());
            return new Dictionary()(new List

    Or, the most "correct" solution in my eyes, for completeness and consistency, would be to create a simple data container class to hold the two lists. This provides a consumer with strongly-typed, good statically compiled (read: intellisense-enabled) return values to work with. The class can be nested right next to the method.

提交回复
热议问题