LINQ query to get result
I have Student list with below data
/*-----------------------
|Student |
-------------------------
| ID | Name | Dept |
-------------------------
| 101 | Peter | IT |
| 102 | John | IT |
| 103 | Ronald | Mech |
| 104 | Sam | Comp |
-----------------------*/
Other list say Extra with below data
/*----------------------
| StudentId | Dept |
------------------------
| 101 | Civil |
| 103 | Chemical |
----------------------*/
Now I want following result
/*-------------------------
|Student |
---------------------------
| ID | Name | Dept |
---------------------------
| 开发者_StackOverflow101 | Peter | Civil |
| 102 | John | IT |
| 103 | Ronald | Chemical |
| 104 | Sam | Comp |
-------------------------*/
Currently I have written below logic:
foreach(item in Extra)
{
//Search item in Student list
//Update it
}
I need more efficient way (don't want to use iteration) using LINQ.
Try something like this. Didn't test it though.
var query = from s in student
join e in extra on s.ID == e.StudentId
select new {s.ID, s.Name, (e.Dept != null) ? e.Dept:s.Dept};
LINQ is using iteration internally, too, so there is no performance benefit in using LINQ. Because LINQ has very general implementations, it might even be slower, because it can't make assumptions about your data, which you can make in your custom loop.
精彩评论