Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map a list of objects on another one with condition

I have two lists. One of them has an Id

var a = new List<MyModel>
            {
                new MyModel()
                {
                    id = 1,
                    prop1 = 1,
                    prop2 = 1
                },
                new MyModel()
                {
                    id = 2,
                    prop1 = 2,
                    prop2 = 3
                },
            };

and another one hasn’t, but they are identical on combination of prop1 and prop2

var b = new List<MyModel>
            {
                new MyModel()
                {
                    prop1 = 1,
                    prop2 = 1
                },
                new MyModel()
                {
                    prop1 = 2,
                    prop2 = 3
                },
            };

I need to populate list b with ids from list a when a.prop1 = b.prop1 && a.prop2 == b.prop2 but I don’t know how to write this linq properly

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The two list are always identical, but unordered. I think I can sort them and just assign them one by one, but I wonder if there another way

>Solution :

This works for me:

var query =
    from bb in b
    join aa in a on new { bb.prop1, bb.prop2 } equals new { aa.prop1, aa.prop2 }
    select new { bb, aa.id };
    
foreach (var q in query)
    q.bb.id = q.id;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading