How to project an object to a list using Linq?

I always need to delete objects before sending them over the wire.

Background:

Position is the tough rival that LINQ to SQL generated based on my table. It stores maternal data data.

SPosition is a lightweight object that only stores my latitude and length.

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 it up a bit?

+4
source share
5 answers
 var spositions = positions.Select( position => new SPosition { latitude = position.Latitude, longitude = position.Longitude }).ToList(); 
+12
source
 return positions .Select(x => new SPosition { latitude = x.Latitude, longitude = x.Longitude }) .ToList() .SerializeToJson<List<SPosition>>(); 
+6
source
 positions.ForEach((p) => {spositions.Add({new SPosition { latitude = p.Latitude, longitude = p.Longitude }; }); 
0
source
 return (from p in positions select new SPosition { latitude = p.Latitude, longitude = p.Longitude }).ToList().SerializeToJson(); 
0
source

First thought:

  return positions.Select(p => new SPosition { latitude = p.Latitude, longitude = p.Longitude }).ToList().SerializeToJson<List<SPosition>>(); 

I did not have the opportunity to check the code, but I think it will work.

0
source

Source: https://habr.com/ru/post/1347982/


All Articles