当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net - Update value in c# dictionary object if value is something

问题描述:

I am trying to update value in c# dictionary object if value is something.

Dictionary<string, int> Section = new Dictionary<string, int>()

{

{"a", 1},

{"b", 0},

{"c", 2},

{"d", 0},

{"e", 0},

{"f", 0},

};

  1. I want to loop through Section object and if value= 2 i want to set it to 1
  2. I want to set the value = 1 from 4th element till end.(i.e, from "d" to "f")

Thanks,

Praveen

I have tried,

foreach(var item in Section)

{

if(item.value == 2)

{

item.value == 1;

}

}

网友答案:
  • I want to loop through Section object and if value= 2 i want to set it to 1

You can look through the Dictionary items, and change the value as needed.

This could be something like:

var itemsToEdit = Section.Where(kvp => kvp.Value == 2).Select(kvp => kvp.Key).ToList();
foreach(var item in itemsToEdit)
     Section[item] = 1;
  • I want to set the value = 1 from 4th element till end.(i.e, from "d" to "f")

Realize that, once you put the values in a dictionary, they lose all ordering. A Dictionary is inherently an unordered collection.

网友答案:

You can't modify a collection within a foreach.

However, you can loop through a derived collection! Note the ToList() to create a separate collection (the Where() just wraps the original collection):

foreach (var item in Section.Where(kvp => kvp.Value == 2).ToList())
{
    Section[item.Key] = 1;
}

Second, we first order the list, then skip the first three elements to get the fourth element onward:

foreach (var item in Section.OrderBy(kvp => kvp.Key).Skip(3).ToList())
{
    Section[item.Key] = 1;
}
网友答案:

1st:

foreach (var key in Section.Where(item => item.Value == 2).Select(item => item.Key).ToList())
{
    Section[key] = 1;
}

2nd:

foreach (var key in Section.Keys.Where(k=>String.Compare(k, "d", StringComparison.Ordinal)>=0).ToList())
{
    Section[key] = 1;
}
网友答案:
int index = 0;
foreach (int value in Section.Values) {

  if ((index > 3) || (value == 2)) { 
    Section[index] = 1; 
  }

  index++;
}

OR

for (int i = 0; i < Section.Count; i++) {
  if ((i > 3) || (Section[i] == 2)) {
    Section[i] = 1;
  }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: