我有一个字符串数组,我想Dictionary
使用Linq将其转换为 a 。我想和一个元件偶数索引(包括零)是键与和元件奇数索引是值在字典中。我使用以下方法创建了一个字典for loop
:
string[] arr = new string[4];
arr[0] = "John";
arr[1] = "A";
arr[2] = "Luke";
arr[3] = "B";
Dictionary<string, string> myDict = new Dictionary<string, string>();
for (int i = 0; i < arr.Length - 1; i += 2)
{
myDict.Add(arr[i], arr[i + 1]);
}
//myDict -> { { "John", "A" },{"Luke","B"} }
Run Code Online (Sandbox Code Playgroud)
现在我很好奇如何用LINQ 做到这一点ToDictionary()
:
myDict = arr.ToDictionary();
Run Code Online (Sandbox Code Playgroud) 假设我有一个名单names
:
List<string> names = new List<string> { "Mike", "Steve", "Alan", "John" };
Run Code Online (Sandbox Code Playgroud)
现在,如果我List<T>.Sort
在列表中使用该方法names
:
names.Sort();
Run Code Online (Sandbox Code Playgroud)
该列表names
将被排序:
"艾伦","约翰","迈克","史蒂夫"
假设我使用LINQ OrderBy
而不是Sort
初始列表names
:
names.OrderBy(x => x);
Run Code Online (Sandbox Code Playgroud)
初始列表names
不会被排序:
"迈克","史蒂夫","艾伦","约翰"
我知道如果我想names
用LINQ 对列表进行排序OrderBy
我必须将查询分配给变量:
var orderedNames = names.OrderBy(x => x);
Run Code Online (Sandbox Code Playgroud)
初始列表names
保持未排序,但orderedNames
将保存初始列表的排序名称:
"艾伦","约翰","迈克","史蒂夫"
我很好奇为什么没有编译器警告没有分配给变量的LINQ查询,因为调用names.OrderBy(x => x);
而不首先将它分配给变量是没用的.
是否有可能比一个更多的单词,我创建了一个计时器,它检查文本框中输入的内容,如果输入的密码更改了图片,那么我的另一个如果功能不起作用,我怎么能做类似的东西这个:
声明代码,我需要这样的东西: if (metroTextBox1.Text == "byby", "cow", "root")
if (metroTextBox1.Text == "byby")
{
Image img = Properties.Resources.Good_Pincode_48px; // Right'as
metroTextBox1.Icon = img;
}
else
{
// new wrong().Show();
Image img = Properties.Resources.Wrong_Pincode_48px; // Wrong'as
metroTextBox1.Icon = img;
}
Run Code Online (Sandbox Code Playgroud)