I have a peice of code where i pack several type of object in an collection of object type. They need to be inserted in a database. I use EF core 2.1 and a popular extention know as EFCore.BulkExtensions below the code:
List<object> mappedContent = MapContent(elements, mappings);// a million records
List<typeA> tAlist= new List<typeA>();
List<typeB> tBlist= new List<typeB>();
List<typeC> tClist= new List<typeC>();
foreach (var record in mappedContent)
{
switch (record.GetType().Name)
{
case "TypeA":
tAlist.Add((TypeA)record);
break;
case "typeB":
tBlist.Add((typeB)record);
break;
case "typeC":
tClist.Add((typeC)record);
break;
default:
Throw new Exception(" Unknown type");
}
}
context.BulkInsert(tAlist);
context.BulkInsert(tBlist);
context.BulkInsert(tClist );
I have more than 20 different objects type and i'm wondering if i can avoid some repetition in the code. Also, i want to do this without affecting performance or even improve the current performance which is quite acceptable thanks to the library that i'm using.
Many thanks in advance
B
Sounds like a job for OfType:
Filters the elements of an IEnumerable based on a specified type.
var tAlist = mappedContent.OfType<TypeA>();
// do wonderful fun stuff with a list of TypeA
Note, performance wise this will probably be better than what you were using. However the source to OfType is basically:
foreach (object obj in source)
{
if (obj is TResult) yield return (TResult)obj;
}
Its basically time complexity O(n) for every time you call it.
If you want a more efficient approach yet more verbose, similar to what you have, yet more modern and performant approach. You could use C# 7.0 Pattern Matching in a switch:
foreach (var record in mappedContent)
switch (record )
{
case TypeA typeA:
tAlist.Add(typeA);
break;
...
It will give you flat O(n), though you will have to make 20 lists etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With