Wednesday, 15 July 2015

c# - Linq How to Join and get 2 tables values -



c# - Linq How to Join and get 2 tables values -

i have 2 tables , want match 2 id values.

first table

id - 1, 2, 3, 4, 5 departmentid - 2, 4, 5, 2, 1

second table

id- 1, 2, 10, 30, 40

i want match first table's id's sec table's id's can departmentid values.

i need virtual result:

id- 1, 2, 10, 30, 40 departmentid -2, 4, null, null, null

here code:

(int = 0; < model1.count(); i++) { model1[i].departmentid= model2.firstordefault(k => k.id== model1[i].id).departmentid; }

i error:

an exception of type 'system.nullreferenceexception' occurred in iyp.userinterfacelayer.dll not handled in user code

i think loop fails because of can't find 10, 30, 40 id values. if id values same in 2 tables( id = 1,2,3,4,5) loop works.

how can linq?

you looking left bring together in linq. seek this:-

var query = emp2 in employee2 bring together emp1 in employee1 on emp2.id equals emp1.id allemployees result in allemployees.defaultifempty() select new { id = emp2.id, deptid = result == null ? "no department" : result.departmentid.tostring() };

where have used next types:-

var employee1 = new[] { new { id = 1, departmentid = 2 }, new { id = 2, departmentid = 4 }, new { id = 3, departmentid = 5 }, new { id = 4, departmentid = 2 }, new { id = 5, departmentid = 1 }, }; var employee2 = new[] { new { id = 1 }, new { id = 2 }, new { id = 10 }, new { id = 30 }, new { id = 40 }, };

complete working fiddle.

c# asp.net-mvc linq

No comments:

Post a Comment