简体   繁体   中英

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 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM