Reputation: 391
I have a class with 5 members. like that:
class Demo
{
public int id;
public string name;
public string color;
public int 4th_member;
public int 5th_member;
}
I have list of this class.
for the 4th_member
, and 5th_member
, I have 2 list of dictionary with int key and int value. (one for 4th, and the second for 5th)
I want to update these members, according to the dictionary.
like, if dictionary's key = id, then update 4th_member
to be value of Dictionary.
I hope my question is clear enough.
Upvotes: 0
Views: 260
Reputation: 2099
I tested the below code its working fine.
Hope this will solve your problem if I have understood your question properly
var demo = demoTest.Select(s =>
{
s.Fourthth_member = dic.GetValueFromDictonary(s.Fourthth_member);
s.Fifthth_member = dic1.GetValueFromDictonary(s.Fifthth_member);
return s;
}).ToList();
//Extension method
public static class extMethod
{
public static int GetValueFromDictonary(this Dictionary<int, int> dic, int key)
{
int value = 0;
dic.TryGetValue(key, out value);
return value;
}
}
Upvotes: 1
Reputation: 37299
linq is not used for updating data but for queries. This is a possible solution:
foreach(var demo in demoList)
{
if(dictionaries[0].ContainsKey(demo.id))
{
demo.member4 = dictionaries[0][demo.id];
}
if (dictionaries[1].ContainsKey(demo.id))
{
demo.member5 = dictionaries[1][demo.id];
}
}
Or with the TryGetValue
foreach(var demo in demoList)
{
int value;
if(dictionaries[0].TryGetValue(demo.id, out value))
{
demo.member4 = value;
}
if (dictionaries[1].TryGetValue(demo.id, out value))
{
demo.member5 = value;
}
}
Upvotes: 1