Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Multiple Objects Single LINQ EF Method

List<MyObject> objects = await item.tables.ToAsyncEnumerable()
                               .Where(p => p.field1 == value)
                               .Select(p => new MyObject(p.field1,p.field2))
                               .ToList();

^ I have something like that, but what i'm wondering, is there anyway way to add a second object creation, in the same select? eg. new MyObject(p.field3,p.field4) ? and add it to the same list? order does not matter.

I know could do this with multiple calls to database or splitting up lists into sections, but is there way to do this in single line?

like image 366
TheBreadman Avatar asked Sep 18 '26 01:09

TheBreadman


2 Answers

You could create it as a tuple.

List<Tuple<MyObject1, MyObject2>> = query.Select(x => Tuple.Create(
    new MyObject1
    {
        // fields
    },
    new MyObject2
    {
        //fields
    }))
    .ToList();

From my testing in Linqpad, it seems that this will only hit the database once.

Alternatively, you could just select all the fields you know you'll need from the database to create both:

var myList = query.Select(x => new { FieldA = x.FieldA, FieldB = x.FieldB }).ToList(); //hits db once
var object1s = myList.Select(x => new MyObject1(x.FieldA));
var object2s = myList.Select(x => new MyObject1(x.FieldB));
var bothLists = object1s.Concat(object2s).ToList();
like image 164
DLeh Avatar answered Sep 19 '26 18:09

DLeh


What you'd want to do is use the SelectMany method in linq. Which will select all the items from an array. The array can be created anonymously as seen below.

List<MyObject> objects = await item.tables.ToAsyncEnumerable()
                               .Where(p => p.field1 == value)
                               .SelectMany(p => new []{new MyObject(p.field1,p.field2), new MyObject(p.field3,p.field4)})
                               .ToList();

Hope that solves you problem!

like image 29
Daniel Hesslow Avatar answered Sep 19 '26 18:09

Daniel Hesslow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!