将2列存储到List中

时间:2011-12-12 16:55:21

标签: c# visual-studio-2010 list c#-4.0 multidimensional-array

如何在List

中存储来自2列(来自数据库)的数据
List<string> _items = new List<string>();

感谢任何帮助

8 个答案:

答案 0 :(得分:49)

您创建一个代表含有2列的行的类:

public class Foo
{
    // obviously you find meaningful names of the 2 properties

    public string Column1 { get; set; } 
    public string Column2 { get; set; }
}

然后存储在List<Foo>

List<Foo> _items = new List<Foo>();
_items.Add(new Foo { Column1 = "bar", Column2 = "baz" });

答案 1 :(得分:21)

使用像KeyValuePair

这样的元组结构
List<KeyValuePair<string, string>> _items = new List<KeyValuePair<string, string>>();
_items.Add(new KeyValuePair<string, string>(foo, bar));

答案 2 :(得分:7)

我会使用一个类

 List<MyDataClass> _items = new List<MyDataClass>();

 public class MyDataClass
 {
     public string Value1 { get; set; }
     public string Value2 { get; set; }
 }

答案 3 :(得分:3)

您可以创建一个新类来保存数据,也可以使用内置的Tuple<>类。 http://msdn.microsoft.com/en-us/library/system.tuple.aspx

此外,如果其中一列包含某种类型的唯一ID,您还可以考虑使用Dictionary<>

答案 4 :(得分:1)

它是关于如何从新的两列列表中检索数据

List<ListTwoColumns> JobIDAndJobName = new List<ListTwoColumns>();
    for (int index = 0; index < JobIDAndJobName.Count;index++)
            {
                ListTwoColumns List = JobIDAndJobName[index];
                if (List.Text == this.cbJob.Text)
                {
                    JobID = List.ID;
                }
            }

答案 5 :(得分:0)

你也可以制作列表数组

List<string> [] list= new List<String> [];
list[0]=new List<string>();
list[1]=new List<string>();

list[0].add("hello");
list[1].add("world");

答案 6 :(得分:0)

您可以这样做:

List<IList<string>> cols = new List<IList<string>>();

您可以设置所需的列数。

cols.Add(new List<string> { "", "", "","more","more","more","more","..." });

答案 7 :(得分:0)

我知道这个问题已经很老了,现在您可能已经找到答案并且已经弄清楚您需要什么,但我想添加一些可能在未来对某人有所帮助的内容。

坦率地说,目前最好的答案来自@csharptest.net,但它有严重的性能缺陷,所以这是我的方法,这是基于使用 Dictionary<TKey, TValue>

的建议的答案
private Dictionary<string, string> _items = new Dictionary<string, string>();  

// if you need to check to see if it exists already or not
private void AddToList(string one, string two)  
{  
    if (!_items.ContainsKey(one))  
        _items.Add(one, two);  
}

// you can simplify the add further
private void AddToList(string one, string two)  
{  
    _items[one] = two;  

    // note if you try to add and it exists, it will throw exception,
    // so alternatively you can wrap it in try/catch - dealer's choice
}