2013-03-13 94 views
1

是否可以在LINQ查询中为SELECT制作模板?现在我有6方法使用完全相同的SELECT,我想尽可能使用模板。选择模板

这是我正在使用的代码,当我想对选择进行更改时,我必须在代码中的许多位置更改相同的内容。

result = query.Select(b => new 
{ 
    route_id = b.b.route_id, 
    name = b.b.name, 
    description = b.b.description, 
    distance = b.b.distance, 
    distance_to_route = (int)b.distance_to_from_me, 
    departure_place = b.b.departure_place, 
    arrival_place = b.b.arrival_place, 
    owner = b.b.user.username, 
    average_rating = b.avg_rating, 
    is_favorite = b.is_favorite, 
    date = b.b.date, 
    attributes = b.b.route_attributes.Select(c => 
     c.route_attribute_types.attribute_name), 
    coordinates = b.b.coordinates.Select(c => 
     new coordinateToSend { sequence = c.sequence, 
      lat = c.position.Latitude, 
      lon = c.position.Longitude }) 
}); 
+10

为什么不使用具有适当构造函数的类? – 2013-03-13 10:25:41

+0

尝试一些像AutoMapper的mappers,但也与Tim的建议 – TalentTuner 2013-03-13 10:28:10

+0

所以我可以创建一个类为我创建选择? – user2049921 2013-03-13 10:31:45

回答

1

这里是你可以做到这一点的一种方式一个简单的例子:

在你的榜样,你的源类型转换为匿名类型。您可以创建一个类来表示您的转换/结果类型,例如:

public class ResultClass 
    { 
     public string ResultPropA { get; set; } 
    } 

有关示例的缘故,可以说下面是你的源类的定义:

public class SourceClass 
    { 
     public string SourcePropA { get; set; } 
    } 

现在,你有类型定义,您可以创建扩展方法将源类的集合转换为结果类的集合:

public static class SourceToResultRepository 
    { 
     public static IEnumerable<ResultClass> ConvertSourceToResult 
      (this IEnumerable<SourceClass> source) 
     { 
      return source.Select(s => new ResultClass 
      { 
       ResultPropA = s.SourcePropA 
       //Add all other property transformations here 
      }); 
     } 
    } 

A这里有一个例子说明如何在需要执行转换的地方使用它:

//Extension usage: 
var result = Database.Source.ConvertSourceToResult(); 

//Direct usage: 
var result = SourceToResultRepository.ConvertSourceToResult(Database.Source);