选择模板 [英] Select template
问题描述
是否可以在LINQ
查询中为SELECT
创建模板?现在,我有6
方法使用完全相同的SELECT,如果可能的话,我想使用模板.
Is it possible to make a template for SELECT
in a LINQ
query? Right now I have 6
methods that uses the exact same SELECT, i would like to use a template if possible.
这是我正在使用的代码,当我想更改选择内容时,必须在代码中的很多地方更改相同的内容.
This is the code I'm using, when I want to make a change to the select I have to change the same thing at so many places in my code.
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 })
});
推荐答案
以下是您可以执行此操作的一种简单示例:
Here is a simple example of one way you could do this:
在您的示例中,您正在将源类型转换为匿名类型.您可以创建一个类来表示您的转换/结果类型,例如:
In your example, you're converting the source type to an anonymous type. You could create a class to represent your converted/result type, for example:
public class ResultClass
{
public string ResultPropA { get; set; }
}
为示例起见,可以说以下是您的源类的定义:
For examples sake, lets say the following was the definition of your source class:
public class SourceClass
{
public string SourcePropA { get; set; }
}
现在,您已经为源和结果对象提供了类型定义,您可以创建一个扩展方法,将源类的集合转换为结果类的集合:
Now that you have type definitions for your source and result objects, you can create an extension method to convert a collection of your source class to a collection of your result class:
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
});
}
}
下面是一个如何在需要执行转换的地方使用它的示例:
And here is an example of how you could use it wherever you need to perform the transformation:
//Extension usage:
var result = Database.Source.ConvertSourceToResult();
//Direct usage:
var result = SourceToResultRepository.ConvertSourceToResult(Database.Source);
这篇关于选择模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!