【发布时间】:2012-01-18 15:43:27
【问题描述】:
如何将来自 2 列(来自数据库)的数据存储在列表中
List<string> _items = new List<string>();
感谢任何帮助
【问题讨论】:
-
字典?列表>?
标签: c# visual-studio-2010 list c#-4.0 multidimensional-array
如何将来自 2 列(来自数据库)的数据存储在列表中
List<string> _items = new List<string>();
感谢任何帮助
【问题讨论】:
标签: c# visual-studio-2010 list c#-4.0 multidimensional-array
你创建一个类来表示一行有 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" });
【讨论】:
DataTextField 和 DataValueField 属性(假设您正在谈论 ASP.NET ListBox 控件)设置为相应的属性名称。例如:ListBox1.DataTextField = "Column1";。如果您正在进行 WinForm 开发,您正在寻找的两个属性称为 DisplayMember 和 ValueMember。
使用像KeyValuePair这样的元组结构
List<KeyValuePair<string, string>> _items = new List<KeyValuePair<string, string>>();
_items.Add(new KeyValuePair<string, string>(foo, bar));
【讨论】:
我会使用一个类
List<MyDataClass> _items = new List<MyDataClass>();
public class MyDataClass
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
【讨论】:
您可以创建一个新类来保存数据,也可以使用内置的Tuple<> 类。 http://msdn.microsoft.com/en-us/library/system.tuple.aspx
此外,如果其中一列包含某种唯一 ID,您还可以考虑使用 Dictionary<>。
【讨论】:
是关于如何从新的两列列表中检索数据
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;
}
}
【讨论】:
我知道这个问题已经很老了,现在你可能已经得到了答案,并且已经弄清楚了你需要什么,但我想添加一些可能在未来帮助某人的东西。
坦率地说,目前最好的答案来自@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
}
【讨论】:
你也可以制作列表数组
List<string> [] list= new List<String> [];
list[0]=new List<string>();
list[1]=new List<string>();
list[0].add("hello");
list[1].add("world");
【讨论】:
你可以这样做:
List<IList<string>> cols = new List<IList<string>>();
您可以设置所需的列数。
cols.Add(new List<string> { "", "", "","more","more","more","more","..." });
【讨论】: