0

I have a c# method which passes a dictionary with generics, for example:

private void SaveData<T>(Dictionary<string, T> results) where T : class
{
   var listOfResults = results.Select(x => x.Value).ToList();     

   // If T is a list
   if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(List<>))
   {
      // HELP HERE, how do I collapse the list of lists?
   }
   else 
   {
      SaveToTheDatabase(listOfResults);
   }
}

We know that T could be a single value or it could be a list of values. The first if statement is supposed to check if T is a list. The else assumes it's a single value.

The spot where I have the comment, HELP HERE, how do I collapse the list of lists?

Chase W.
  • 1,343
  • 2
  • 13
  • 25
  • what does the signature for `SaveToTheDatabase` look like? – Daniel A. White Jun 22 '18 at 16:51
  • SaveToTheDatabase is a private variable with the type of Action> – Chase W. Jun 22 '18 at 16:52
  • @MikeMcCaughan, mine is flatten list in LINQ with generics. Different question – Chase W. Jun 22 '18 at 16:53
  • Wouldn't you want to check it T is a list before creating your `listOfResults`? – itsme86 Jun 22 '18 at 16:53
  • I don't see how... that question uses generics too, it just happens to be that `T` in that question is `int`. – Heretic Monkey Jun 22 '18 at 16:54
  • @itsme86 I'm flattening the Dictionary into the variable listOfResults. – Chase W. Jun 22 '18 at 16:54
  • So your `listOfResults` of type `List` is actually `List>`, and you don't know the `U`. The question by @DanielA.White makes sense because looks like you have to convert it to `List` and pass it to a generic method (not action) with `U` generic argument. – Ivan Stoev Jun 22 '18 at 16:59
  • 1
    @DavidG How `T` could be `List`? – Ivan Stoev Jun 22 '18 at 17:00
  • @DavidG, @IvanStoev is correct. T could be a List. I tried playing around with this: `var tmp = listOfResults.Cast>().SelectMany(x => x).ToList();` which didn't work because the complier didn't know how to cast that. – Chase W. Jun 22 '18 at 17:08
  • Yeah, of course! Better to just have two methods where one takes a `Dictionary>` instead. Then you can get rid of the pesky reflection code. – DavidG Jun 22 '18 at 17:09
  • 1
    DavidG is correct -- this works much better if you have *two* methods, one which saves a `Dictionary` and one which saves a `Dictionary>` If you are doing a type test in a generic, that is a strong sign that you actually need to have two methods. Alternatively, move the problem into SaveToTheDatabase, and make *it* flatten the sequence it receives. – Eric Lippert Jun 22 '18 at 17:41

0 Answers0