2

I have a method call as follows:

splitByRegex(regexPattern, lines, ref lineIndex, capacity, result =>
{
      List<object> res = result.Select(selector).ToList();
      MessageBox.Show(res[0].GetType().ToString());
      collection.GetType().GetMethod("AddRange").Invoke(collection, new object[] { res });
});

splitByRegex method will split the data and will give back result.

I have to add the obtained result to the generic collection.

Type of selector function: Func<Tuple<string, string, string>, object>

Sample selector Function: x => new Merchant { MerchantName = x.Item1, Count = Convert.ToInt64(x.Item2), Percentage = Convert.ToDecimal(x.Item3) }

While executing AddRange method call using reflection: collection.GetType().GetMethod("AddRange").Invoke(collection, new object[] { res });

I am getting following error:

Object of type 'System.Linq.Enumerable+WhereSelectListIterator2[System.Tuple3[System.String,System.String,System.String],System.Object]' cannot be converted to type 'System.Collections.Generic.IEnumerable`1[Processing.Merchant]'.

When I try to print the type of any one object from the List<object> res MessageBox.Show(res[0].GetType().ToString());, it shows it as Merchant type object. So why am I getting this error?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Nilesh Barai
  • 1,312
  • 8
  • 22
  • 48
  • Because `List` isn't a `List` or an `IEnumerable`, in the same way that a `List` isn't a `List` even (where `Cat : Animal`), even if the list only contains cats. – ProgrammingLlama Oct 25 '19 at 04:54
  • Eric's answer [here](https://stackoverflow.com/a/1817341/3181933) illustrates it particularly well. – ProgrammingLlama Oct 25 '19 at 04:55
  • @John - how do I convert it dynamically? Will I have use an interface coz multiple type can come as a part of selector function? – Nilesh Barai Oct 25 '19 at 04:56
  • I'm not sure if there is a particularly good way to do that. Showing us a little more of your method help (i.e. can it be made generic?) – ProgrammingLlama Oct 25 '19 at 04:58

1 Answers1

2

@John - Thanks for pointing me to Eric's post. This makes it clear. I fixed it by not calling AddRange method, however call Add method of the generic collection for each element in the obtained result.

splitByRegex(regexPattern, lines, ref lineIndex, capacity, result =>
{
     MethodInfo method = collection.GetType().GetMethod("Add");
     result.Select(selector).ToList().ForEach(item => method.Invoke(collection, new object[] { item }));
});
Nilesh Barai
  • 1,312
  • 8
  • 22
  • 48