从字符串获取字符串数组的值

时间:2016-03-15 19:43:17

标签: c# arrays string

我有一个包含元素的字符串数组。这些元素由单词和颜色组成:

Array [0]: word = "Word1", Color = "Green"
Array [1]: word = "Word2", Color = "Blue"
Array [2]: word = "Word3", Color = "Yellow"

是否可以从单词中恢复(一行)颜色? 没有数组中的循环?

的问候,

4 个答案:

答案 0 :(得分:2)

您可以使用LINQ First()方法:

Color word2color = elementArray.First(e => e.word == "Word2").Color

答案 1 :(得分:2)

但是,根据您的意见:

// Assuming your object looks like this from your question
class MyObject {
        public string Word { get; set; }
        public string Color { get; set; }
}

你可以这样做:

MyObject[] data = ... ;
var fromWord1 = data.First(x => x.Word == "Word1").Color;
Console.WriteLine(fromWord1);

但是,最好使用字典并根据需要抓取它们。

MyObject[] data = ... ;
var dict = data.ToDictionary(x => x.Word, x => x.Color);
Console.WriteLine(dict["Word1"]);

答案 2 :(得分:0)

Var myword = "someword";

Var ele = elementArray.FirstOrDefault(e => e.word.ToUpper() == myword.ToUpper());

If(ele != null) 
 // do something with ele.Color

答案 3 :(得分:0)

此代码显示如何将颜色存储在数组中。

代码:

 class Word {
            public string Word { get; set; }
            public string Color { get; set; }
    }

    class array
    {
        public Word[] array1 { get; set; }
        public Word[] array2 { get; set; }
    }

    array[] array = new array[1];
    array[0] = new array()
    {
        array1 = new Word[]
        {
            new Word()
            {
                Word = "Word1",
                Color = "Blue"
            },
            new Word()
            {
                Word = "Word2",
                Color = "Green"
            },
            new Word()
            {
                Word = "Word3",
                Color = "Yellow"
            }
        },
        array2 = new Word[]
        {
            new Word()
            {
                Word = "Word4",
                Color = "Black"
            }
        }
    };