我如何在C#中使用LINQ。选择时要保持类型? [英] How can I maintain type when using LINQ .Select in C#?
问题描述
我试图返回一组不同的正在使用的子串第一个修整的结果,但是当我打电话,请选择将其转换为匿名类型。我似乎无法得到这个维持类型列表。我只需要返回在选择方法指定的字段
I'm trying to return a Distinct set of results that are first trimmed using Substring, but when I call "Select" it converts it to an anonymous type. I can't seem to get this to maintain the type "List". I only need to return the fields specified in the Select method.
public List<Facility> GetFacilities() {
var facilities = new List<Facility>();
facilities = _facilityRepository.GetAll().ToList();
var facReturnList =
facilities.Where(x => x.Fac_Name = "Something")
.OrderBy(x => x.Fac_Name).ToList();
var facReturnList2 =
facReturnList.Select(x =>
new { ID = x.Fac_Name.Substring(0, 6),
Fac_Name = x.Fac_Name.Substring(0, 3) })
.Distinct().ToList();
return facReturnList2;
}
我尝试添加列表<基金>
在新
,但它说,这些属性( ID
和 Fac_Name
)不会在设施中定义。
I tried adding List<Facility>
after new
, but it says those properties (ID
and Fac_Name
) aren't defined in Facility.
推荐答案
是否要初始化新的 ?基金
与结果的实例
Do you want to initialize new Facility
instances with your results?
var facReturnList2 = facReturnList.Select(x => new Facility { ID = // ...
^ concrete type initializer
响应修改:在选择
运营商,你需要指定的类型的元素的要初始化,而不是他们的名单。您之前的代码似乎表明, Fac_Name
的是的在基金
,定义,但它显然不会告发
Response to edit: Inside the Select
operator, you need to specify the type of the elements that you want to initialize, not their list. Your prior code seems to indicate that Fac_Name
is defined in Facility
, but it obviously wouldn't be defined in List<Facility>
.
这篇关于我如何在C#中使用LINQ。选择时要保持类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!