Multiple parameters in a List. How to create without a class?

后端 未结 10 1994
不知归路
不知归路 2020-12-12 23:25

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:

相关标签:
10条回答
  • 2020-12-13 00:22

    If you are using .NET 4.0 you can use a Tuple.

    List<Tuple<T1, T2>> list;
    

    For older versions of .NET you have to create a custom class (unless you are lucky enough to be able to find a class that fits your needs in the base class library).

    0 讨论(0)
  • 2020-12-13 00:22

    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.

    0 讨论(0)
  • 2020-12-13 00:27

    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

    0 讨论(0)
  • 2020-12-13 00:29

    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;
            }
    
    0 讨论(0)
提交回复
热议问题