C# 如何获取 List<object> 的单个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19206676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:23:30  来源:igfitidea点击:

How to get single value of List<object>

c#asp.net

提问by vyclarks

I'm a new to ASPX, hope you dont mind if my problem is so simple with somebody.

我是 ASPX 的新手,希望您不介意我的问题对某人来说如此简单。

I use a List<object> selectedValues;

我用一个 List<object> selectedValues;

selectedValues=...list of object(item1, item2,..)

Each object has 3 fields: id, title, and content.

每个对象有3个字段:idtitle,和content

foreach (object[] item in selectedValues)
{
  foreach (object value in item)
  {
    string result += string.Format("{0}    ", value);
    Textbox1.Text= result;--> all field is displayed in one Textbox.
  }
}

My problem is: how can I get the single field, I mean:

我的问题是:我怎样才能得到单个字段,我的意思是:

foreach (object value in item)
            {
                TextBox1.Text = id...???
                TextBox2.Text= title...???
                TextBox3.Text= content...???
}

采纳答案by Alex

You can access the fields by indexing the object array:

您可以通过索引对象数组来访问字段:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

也就是说,如果项目数量不是动态的,您最好将字段存储在您自己的一个小类中:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

然后你可以这样做:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

回答by User1551892

Define a class like this :

定义一个这样的类:

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

我试着画一个草图,你可以在很多方面改进它。您可以定义结构,而不是定义类“myclass”。