列表<>包含数字和文本

本文关键字:文本 数字 包含 列表 | 更新日期: 2023-09-27 18:34:16

是否有类似于二维数组的List<>? 每个条目都有一个数字和文本。

列表<>包含数字和文本

您可以使用

Dictionary<int,String>

样本:

Dictionary<int,string> samp = new Dictionary<int,string>();
dictionary.Add(1, "text1");
dictionary.Add(2, "text2");

或者,有一个定义您的需求的自定义类

public class Sample
{
   public int Number;
   public string Text;
}

样本:

List<Sample> req = new List<Sample>();
Sample samObj = new Sample();
samObj.Number = 1;
samObj.Text = "FirstText";
req.Add(samObj);

有很多选项,我为您描述其中的一些

  1. 使用Dictionary<int, string>
    优点: 非常快速的
    查找缺点:你不能有两个数字相同的字符串,你没有List

    var list2d = new Dictionary<int, string>();
    list2d[1] = "hello";
    list2d[2] = "world!";
    foreach (var item in list2d)
    {
        Console.WriteLine(string.Format("{0}: {1}", item.Key, item.Value);
    }
    
  2. 使用Tuple<int, string>
    优点:非常简单方便的工具,您有一个List
    缺点Tuple是不可变的,一旦创建它们就无法更改它们的值,降低了代码的可读性(Item1Item2

    var list2d = new List<Tuple<int, string>>();
    list2d.Add(new Tuple(1, "hello"));
    list2d.Add(Tuple.Create(1, "world");
    foreach (var item in list2d)
    {
        Console.WriteLine(string.Format("{0}: {1}", item.Item1, item.Item2);
    }
    
  3. 使用定义的类,
    优点:您有一个List,非常可
    定制缺点: 你应该写更多的代码来设置

    public class MyClass
    {
       public int Number { get; set; }
       public string Text { get; set; }
    }
    var list2d = new List<MyClass>();
    list2d.Add(new MyClass() { Number = 1, Text = "hello" });
    list2d.Add(new MyClass { Number = 2, Text = "world" });
    foreach (var item in list2d)
    {
        Console.WriteLine(string.Format("{0}: {1}", item.Number, item.Text);
    }
    

自定义类或字典是不错的选择,您也可以使用元组泛型...

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

字典要求用作键的任何值都必须是唯一的。所以没有独特性就不理想。

如果您不介意多一点代码,则最好使用自定义类,如果您决定要在其中添加其他数据,则可以在以后进行扩展。

元组既快速又简单,但您会失去可读性,并且无法编辑对象。

定义一个包含字符串和 int 属性的类

public class MyClass 
{ 
  public string MyStr {get;set;} 
  public int MyInt {get;set;} 
}

然后创建此类的列表

List<Myclass> myList = new List<MyClass>();
myList.add(new MyClass{MyStr = "this is a string", MyInt=5});

希望能有所帮助

public class DATA
{
    public int number;
    public string text;
}
List<DATA> list = new List<DATA>();