Hi,
I am writing a simple generic update extension for IEnumerable, this method used to join given 2 List of business objects or dictionaries using the given keys and updating the specific field.
public static void Update<TOuter, TInner, TKey>(this IEnumerable<TOuter> outer, IEnumerable<TInner> Inner, Func<TOuter, TKey> OuterKeySelector, Func<TInner, TKey> InnerKeySelector,Action<TOuter,TInner> updator)
{
ILookup<TKey, TInner> innerLookup = Inner.ToLookup(InnerKeySelector, element => element);
foreach (TOuter outerItem in outer)
{
TKey key = OuterKeySelector(outerItem);
if (innerLookup.Contains(key))
{
foreach (TInner innerItem in innerLookup[key])
{
updator(outerItem, innerItem);
}
}
}
}
This works fine in normal objects, for ex:
List<testObject> obj1 = new List<testObject>()
{
new testObject(){fruitId=1,name="mango"},
new testObject(){fruitId=2,name="grapes"},
new testObject(){fruitId=2,name="grapes"},
new testObject(){fruitId=4,name="kivi"},
};
List<testObject> obj2 = new List<testObject>()
{
new testObject(){fruitId=2,name="apple"},
new testObject(){fruitId=4,name="orange"},
};
obj1.Update(obj2,
tx => tx.fruitId,
ty => ty.fruitId,
(tx,ty)=>tx.name=ty.name);
But, i cannot use this method with dictionary,
Dictionary<string, int> first = new Dictionary<string, int>()
{
{"a",1},
{"b",2},
{"c",9},
{"e",5},
};
Dictionary<string, int> second = new Dictionary<string, int>()
{
{"a",8},
{"b",2},
{"e",20}
};
var kk = 0;
first.Update(second,
f1 => f1.Key,
s1 => s1.Key,
(f1, s1) => f1.Value = s1.Value);
it gives the below error
Property or indexer 'System.Collections.Generic.KeyValuePair.Value' cannot be assigned to -- it is read only
I know there is a restriction, by MSDN
Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.
is there a hack/workaround to achive the same functionality in a generic manner?
Cheers