C# 如何在这个例子中使用列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12846455/
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 00:40:01  来源:igfitidea点击:

How to use list in this example

c#arrayslist

提问by a1204773

Lets say i have an array like that (I know that is not possible on c#):

假设我有一个这样的数组(我知道这在 c# 上是不可能的):

string[,] arr = new string[,]
{
    {"expensive", "costly", "pricy", 0},
    {"black", "dark", 0}
};

So how I can add this items on list and how I can add new item between "pricy"and 0? I couldn't find any example on the net.

那么我如何在列表中添加这些项目以及如何在"pricy"0之间添加新项目?我在网上找不到任何例子。

采纳答案by kprobst

Arrays are immutable, so you can't really add or remove items from them. The only thing you can do for example is to copy the items to another array instance, minus the ones you don't want, or do the same but use a higher dimension and add the items you need to add.

数组是不可变的,因此您无法真正添加或从中删除项目。例如,您唯一可以做的就是将项目复制到另一个数组实例,减去您不想要的项目,或者执行相同操作但使用更高的维度并添加您需要添加的项目。

I'd recommend using a List<T>here, where Tcould be a simple type that mirrors the things you're adding to the array. For example:

我建议在List<T>此处使用 a ,其中T可能是一个简单的类型,可以反映您添加到数组中的内容。例如:

class Thing {
    public string Prop1 {get; set; }
    public string Prop2 {get; set; }
    public string Prop3 {get; set; }
    public int Prop4 {get; set; }
}

List<Thing> list = new List<Thing>();

list.Add(new Thing() { Prop1 = "expensive", Prop2 = "costly", Prop3 = "pricy", Prop4 = 0};

Then you can insert items:

然后你可以插入项目:

list.Insert(1, new Thing() { Prop1 = "black", Prop2 = "dark", Prop4 = 0});

Not sure if this would work for you, it depends on whether your 'jagged' data can be made to fit into Thing. Obviously here 'Prop1' and so on would be the actual property names of the data you have in your array.

不确定这是否适合您,这取决于您的“锯齿状”数据是否可以放入Thing. 显然,这里的 'Prop1' 等将是数组中数据的实际属性名称。

回答by Henk Holterman

If you want to Add (Insert) items then do not use arrays. Use List<>.

如果要添加(插入)项目,请不要使用数组。使用List<>.

Your sample might be covered by

您的样本可能包含在

var data = new List<string>[2] { new List<string>(), new List<string> () };

You can then use statements like

然后你可以使用像这样的语句

data[0].Add("expensive");
string s = data[1][1];     // "dark"

It is of course not possible to have 0in a string array or List. You could use nullbut try to avoid it first.

当然不可能有0字符串数组或列表。你可以使用,null但首先尽量避免它。

回答by dgarbacz

You could make it a Dictionary<string,string>, but the key would have to remain unique. You would then be able to loop through like so

您可以将其Dictionary<string,string>设为 ,但密钥必须保持唯一。然后你就可以像这样循环

Dictionary<string,string> list = new Dictionary<string,string>();
foreach(KeyValuePair kvp in list) 
{
    //Do something here
}

回答by D Stanley

Well what do you want a list OF? Right now you've got strings and integers so objectis your common base class

那么你想要一个列表OF吗?现在你有字符串和整数,object你的公共基类也是

You can do a jagged array (an array of arrays):

你可以做一个锯齿状的数组(数组的数组):

object[][] arr = new []
{
    new object[] {"expensive", "costly", "pricy", 0},
    new object[] {"black", "dark", 0}
};

or a list of lists:

或列表列表:

List<List<object>> arr = new List<List<object>> 
{
    new List<object> {"expensive", "costly", "pricy", 0},
    new List<object> {"black", "dark", 0}
};

But both of those seem like bad designs. If you give more information on what you're trying to accomplish you can probably get some better suggestions.

但这两者似乎都是糟糕的设计。如果您提供有关您要完成的工作的更多信息,您可能会得到一些更好的建议。

回答by Anton Baksheiev

Your task is little strange, and i don't understand where it can be useful. But in your context you can do it without Listand so on. You should go through element by indexer(in your example item in string[,] can be get only with TWO indexes).

你的任务有点奇怪,我不明白它在哪里有用。但是在您的上下文中,您可以不用List等等。您应该通过索引器遍历元素(在您的示例项目中 string[,] 只能通过两个索引获得)。

So here solution that works, i did it only for interesting

所以这里的解决方案有效,我这样做只是为了有趣

var arr = new[,]
                          {
                              {"expensive", "costly", "pricy", "0"},
                              {"black", "dark", "0", "0"}
                          };
            int line = 0;
            int positionInLine = 3;
            string newValue = "NewItem";


            for(var i = 0; i<=line;i++)
            {
                for (int j = 0; j <=positionInLine; j++)
                {
                    if (i == line && positionInLine == j)
                    {
                        var tmp1 = arr[line, positionInLine];
                        arr[line, positionInLine] = newValue;

                        try
                        {
                            // Move other elements
                            for (int rep = j+1; rep < int.MaxValue; rep++)
                            {
                                var tmp2 = arr[line, rep];

                                arr[line, rep] = tmp1;

                                tmp1 = tmp2;

                            }
                        }
                        catch (Exception)
                        {

                            break;
                        }
                    }
                }
            }

回答by Ankush Madankar

class Program
{
    static void Main(string[] args)
    {
        List<Array> _list = new List<Array>();

        _list.Add(new int[2] { 100, 200 });
        _list.Add(new string[2] { "John", "Ankush" });

        foreach (Array _array in _list)
        {
            if (_array.GetType() == typeof(Int32[]))
            {
                foreach (int i in _array)
                    Console.WriteLine(i);
            }
            else if (_array.GetType() == typeof(string[]))
            {
                foreach (string s in _array)
                    Console.WriteLine(s);
            }
        }
        Console.ReadKey();
    }
}