How do I project an object into a list using 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 positio开发者_C百科ns) // 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?
var spositions = positions.Select(
position => new SPosition
{
latitude = position.Latitude,
longitude = position.Longitude
}).ToList();
return positions
.Select(x => new SPosition
{
latitude = x.Latitude,
longitude = x.Longitude
})
.ToList()
.SerializeToJson<List<SPosition>>();
positions.ForEach((p) => {spositions.Add({new SPosition { latitude = p.Latitude, longitude = p.Longitude }; });
return (from p in positions
select new SPosition
{
latitude = p.Latitude,
longitude = p.Longitude
}).ToList().SerializeToJson();
First thought:
return positions.Select(p => new SPosition
{
latitude = p.Latitude,
longitude = p.Longitude
}).ToList().SerializeToJson<List<SPosition>>();
Haven't had a chance to test the code, but I think it'll work.
精彩评论