[c#] Multiple parameters in a List. How to create without a class?

This is probably a pretty obvious question, but how would I go about creating a List that has multiple parameters without creating a class.

Example:

var list = new List<string, int>();

list.Add("hello", 1);

I normally would use a class like so:

public class MyClass
{
    public String myString {get; set;}
    public Int32 myInt32 {get; set;}
}

then create my list by doing:

var list = new List<MyClass>();
list.Add(new MyClass { myString = "hello", myInt32 = 1 });

This question is related to c# class list

The answer is


For those wanting to use a Class.

Create a Class with all the parameters you want

Create a list with the class as parameter

_x000D_
_x000D_
class MyClass_x000D_
        {_x000D_
            public string S1;_x000D_
            public string S2;_x000D_
        }_x000D_
_x000D_
List<MyClass> MyList= new List<MyClass>();
_x000D_
_x000D_
_x000D_


To add to what other suggested I like the following construct to avoid the annoyance of adding members to keyvaluepair collections.

public class KeyValuePairList<Tkey,TValue> : List<KeyValuePair<Tkey,TValue>>{
    public void Add(Tkey key, TValue value){
        base.Add(new KeyValuePair<Tkey, TValue>(key, value));
    }
}

What this means is that the constructor can be initialized with better syntax::

var myList = new KeyValuePairList<int,string>{{1,"one"},{2,"two"},{3,"three"}};

I personally like the above code over the more verbose examples Unfortunately C# does not really support tuple types natively so this little hack works wonders.

If you find yourself really needing more than 2, I suggest creating abstractions against the tuple type.(although Tuple is a class not a struct like KeyValuePair this is an interesting distinction).

Curiously enough, the initializer list syntax is available on any IEnumerable and it allows you to use any Add method, even those not actually enumerable by your object. It's pretty handy to allow things like adding an object[] member as a params object[] member.


List only accepts one type parameter. The closest you'll get with List is:

 var list = new List<Tuple<string, int>>();
 list.Add(Tuple.Create("hello", 1));

Another solution create generic list of anonymous type.

 var list = new[]
 { 
    new { Number = 10, Name = "Smith" },
    new { Number = 10, Name = "John" } 
 }.ToList();

 foreach (var item in list)
 {
    Console.WriteLine(item.Name);
 }

This also gives you intellisense support, I think in some situations its better than Tuple and Dictionary.


Get Schema Name and Table Name from a database.

        public IList<Tuple<string, string>> ListTables()
        {

            DataTable dt = con.GetSchema("Tables");

            var tables = new List<Tuple<string, string>>();

            foreach (DataRow row in dt.Rows)
            {
            string schemaName = (string)row[1];
            string tableName = (string)row[2];
            //AddToList();
            tables.Add(Tuple.Create(schemaName, tableName));
            Console.WriteLine(schemaName +" " + tableName) ;
            }
            return tables;
        }

As said by Scott Chamberlain(and several others), Tuples work best if you don't mind having immutable(ie read-only) objects.

If, like suggested by David, you want to reference the int by the string value, for example, you should use a dictionary

Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("string", 1);
Console.WriteLine(d["string"]);//prints 1

If, however, you want to store your elements mutably in a list, and don't want to use a dictionary-style referencing system, then your best bet(ie only real solution right now) would be to use KeyValuePair, which is essentially std::pair for C#:

var kvp=new KeyValuePair<int, string>(2, "a");
//kvp.Key=2 and a.Value="a";
kvp.Key = 3;//both key and
kvp.Value = "b";//value are mutable

Of course, this is stackable, so if you need a larger tuple(like if you needed 4 elements) you just stack it. Granted this gets ugly really fast:

     var quad=new KeyValuePair<KeyValuePair<int,string>, KeyValuePair<int,string>>
                (new KeyValuePair<int,string>(3,"a"),
                new KeyValuePair<int,string>(4,"b"));
//quad.Key.Key=3

So obviously if you were to do this, you should probably also define an auxiliary function.

My advice is that if your tuple contains more than 2 elements, define your own class. You could use a typedef-esque using statement like :

using quad = KeyValuePair<KeyValuePair<int,string>, KeyValuePair<int,string>>;

but that doesn't make your instantiations any easier. You'd probably spend a lot less time writing template parameters and more time on the non-boilerplate code if you go with a user-defined class when working with tuples of more than 2 elements


If appropriate, you might use a Dictionary which is also a generic collection:

Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("string", 1);

If you do not mind the items being imutable you can use the Tuple class added to .net 4

var list = new List<Tuple<string,int>>();
list.Add(new Tuple<string,int>("hello", 1));

list[0].Item1 //Hello
list[0].Item2 //1

However if you are adding two items every time and one of them is unique id you can use a Dictionary


This works fine with me

List<string> myList = new List<string>();
myList.Add(string.Format("{0}|{1}","hello","1") ;


label:myList[0].split('|')[0] 
val:  myList[0].split('|')[1]

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>