创建列表<>及其用途 [英] Creating a list<> and its uses

查看:102
本文介绍了创建列表<>及其用途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如何将所有字段存储在列表中形式?任何帮助,将不胜感激.谢谢.
列表有什么作用/如何帮助呢?

我尝试过的事情:

我尝试使用谷歌搜索,但发现它就像创建对象一样

Hi,

How to store all the fields in the List<> form? any help would be appreciated. thanks.
And what/how does a list help to do?

What I have tried:

i tried googling but i found it is same like creating an object

推荐答案

列表 与创建任何其他对象一样,区别在于它是泛型类型,这意味着您可以在<"和>"字符之间指定列表包含的对象类型.因此,创建列表的一般语法为:
A List is just the same as creating any other object, the difference is that it''s a Generic type, which means that you specify what kind of objects the List holds between the ''<'' and ''>'' characters. So the general syntax for creating a list is:
List<TypeOfObjectsItHolds> nameOfTheListVariable = new List<TypeOfObjectsItHolds>();

例如,如果您想要一个整数列表:

For example, if you want a List of integers:

List<int> list = new List<int>();
for (int i = 0; i < 10; i++)
   {
   list.Add(i * 2);
   }

或字符串列表:

Or a list of strings:

List<string> list = new List<string>();
for (int i = 0; i < 10; i++)
   {
   list.Add(string.Format("The value is {0}", i * 2));
   }

或您自己的课程:

Or your own class:

List<MyClass> list = new List<MyClass>();
for (int i = 0; i < 10; i++)
   {
   list.Add(new MyClass(i));
   }


之后,您可以将列表视为可扩展数组"-您可以使用列表执行与数组相同的任何操作,但是还可以在运行时添加和删除项目:


After that, you can think of a list as a "stretchy array" - you can do anything with it that you can do with an array but you can also add and remove items at runtime:

if (list.Count > 5)
   {
   Console.WriteLine(list[4]);
   list.RemoveAt(3);
   Console.WriteLine(list[4]);
   }

当您事先不知道要保留多少个项目时(例如,当您想从用户那里获得大量数字然后按降序对其进行排序时),它们确实非常方便.您无需询问用户他要输入多少个项目,只需将它们添加到列表中,直到他说这就是您的全部!"即可.

但是,有一些关于性能的警告,我将为您提供一个链接-但当您更熟悉C#和一般的集合时,请记住"该链接以供以后使用:

They are really handy when you don''t know in advance how many items you want to hold - for example when you want to get a load of numbers from the user and then sort them into descending order. Rather than asking the user how many items he is going to enter, you just add them to a list until he says "that''s your lot!".

There are some caveats regarding performance however, which I''ll give you a link to - but "remember" it for later when you are more familiar with C# and collections generally: List<T> - Is it really as efficient as you probably think?[^] rather than read it now!


这篇关于创建列表&lt;&gt;及其用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆