Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I project an object into a list using Linq?

Tags:

c#

linq

I find myself always needing to thin out objects before sending them over the wire.

Background:

Position is a heavy contender, which was generated by LINQ to SQL based off my table. It stores the motherlode of data.

SPosition is a lightweight object, which stores only my latitude and longitide.

Code:

 List<SPosition> spositions = new List<SPosition>();
 foreach (var position in positions)  // positions = List<Position>
 {
    SPosition spos = new SPosition { latitude = position.Latitude, longitude = position.Longitude };
    spositions.Add(spos);
 }

 return spositions.SerializeToJson<List<SPosition>>();

How can I use some LINQ magic to clean this up a bit?

like image 523
George Johnston Avatar asked Dec 02 '22 02:12

George Johnston


1 Answers

var spositions = positions.Select(
                     position => new SPosition
                         {
                             latitude = position.Latitude,
                             longitude = position.Longitude
                         }).ToList();
like image 137
Ed Chapel Avatar answered Dec 05 '22 00:12

Ed Chapel