如何在 C# 中使用 Enumarable 反转一系列元素?
我有两个整数变量,例如
int Max = 10;
int limit = 5;
一个字典,
Dictionary<String , String> MyDict = new Dictionary<string,string>();
我需要用 Max 元素填充字典,如果索引大于或等于 limit ,则该值应该为无。
这是我的示例代码,它将清除我的问题
int j = 1;
for (int i = Max-1; i >= 0; i--)
{
if (i >= limit)
MyDict.Add((j++).ToString(), "None");
else
MyDict.Add((j++).ToString(), i.ToString());
}
,因此结果将类似于
{ "1" "None" }
{ "2" "None" }
{ "3" "None" }
{ "4" "None" }
{ "5" "None" }
{ "6" "4" }
{ "7" "3" }
{ "8" "2" }
{ "9" "1" }
{ "10" "0" }
如何使用 LINQ
或 LAMBDA Expression
执行此操作,
相反可以使用 Enumarable< /code> 这里是
MyDict = Enumerable.Range(0, Max)
.ToDictionary(X => (X + 1).ToString(), X => X >= limit ? "None" : X.ToString());
这个表达式的输出
{ "1" "0" }
{ "2" "1" }
{ "3" "2" }
{ "4" "3" }
{ "5" "4" }
{ "6" "None" }
{ "7" "None" }
{ "8" "None" }
{ "9" "None" }
{ "10" "None" }
但是如何做相反的事情(就像 for
循环的输出)?或者如何修改现有的LINQ
?
提前致谢。
I have two Integer variables like
int Max = 10;
int limit = 5;
and a Dictionary
Dictionary<String , String> MyDict = new Dictionary<string,string>();
I need to fill the dictionary with Max
elements and if the index is greater than or equal to limit
then the value should be none.
Here is my sample code which will clear my question
int j = 1;
for (int i = Max-1; i >= 0; i--)
{
if (i >= limit)
MyDict.Add((j++).ToString(), "None");
else
MyDict.Add((j++).ToString(), i.ToString());
}
so the result will be like
{ "1" "None" }
{ "2" "None" }
{ "3" "None" }
{ "4" "None" }
{ "5" "None" }
{ "6" "4" }
{ "7" "3" }
{ "8" "2" }
{ "9" "1" }
{ "10" "0" }
How to do this using LINQ
or LAMBDA Expression
The reverse can be done using Enumarable
here it is
MyDict = Enumerable.Range(0, Max)
.ToDictionary(X => (X + 1).ToString(), X => X >= limit ? "None" : X.ToString());
Output of this expression
{ "1" "0" }
{ "2" "1" }
{ "3" "2" }
{ "4" "3" }
{ "5" "4" }
{ "6" "None" }
{ "7" "None" }
{ "8" "None" }
{ "9" "None" }
{ "10" "None" }
But how to do the reverse of this (like the output of the for
loop)? Or how can I modify the existing LINQ
?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)