我正在尝试制定一个LINQ查询来选择一个列表的子列表,它满足where条件,如下所示:
List<Entities.Base> bases = this.GetAllBases();
List<Entities.Base> thebases = from aBase in bases
where aBase.OfficeCD == officeCD
select aBase;
其中Base只是一个实体类:
public string BaseCD { get; set; }
public string BaseName { get; set; }
public string OfficeCD { get; set; }
public DateTime EffectiveDate { get; set; }
public DateTime ExpirationDate { get; set; }
我收到错误“无法将System.Collections.Generic.IEnumerable类型隐式转换为System.Collections.Generic.List
所以我尝试应用Cast运算符但是失败了。我现在看到我不想转换元素的类型。我该如何解决这个问题?谢谢!
答案 0 :(得分:10)
这不是一个可以通过“铸造”解决的问题;您获得的查询结果不是列表 - 它是一个延迟执行的序列,它将匹配的项目按按需流式传输。您必须将这些结果实际加载到List<T>
以实现您的目的。例如,Enumerable.ToList
方法将创建一个新列表,使用查询结果填充它,然后将其返回。
一些选择:
var thebases = (from aBase in bases
where aBase.OfficeCD == officeCD
select aBase).ToList();
// fluent syntax
var thebases = bases.Where(aBase => aBase.OfficeCD == officeCD)
.ToList();
// not a LINQ method - an instance method on List<T>.
// Executes immediately - returns a List<T> rather than a lazy sequence
var thebases = bases.FindAll(aBase => aBase.OfficeCD == officeCD);
// "manual" ToList()
var theBases = new List<Entities.Base>();
var matchingBases = from aBase in bases
where aBase.OfficeCD == officeCD
select aBase;
foreach(var matchingBase in matchingBases)
theBases.Add(matchingBase);
答案 1 :(得分:3)
除了@Ani提到的方法之外,您还可以使用LINQ直接在您的类中选择数据,如下所示:
List<Entities.Base> bases = this.GetAllBases();
List<Entities.Base> thebases = new List<Entities.Base>(
from aBase in bases
where aBase.OfficeCD == officeCD
select new Entities.Base {
BaseCD = aBase.BaseCD,
BaseName = aBase.BaseName,
OfficeCD = aBase.OfficeCD,
EffectiveDate = aBase.EffectiveDate,
ExpirationDate = aBase.ExpirationDate
};
答案 2 :(得分:2)
以下是Joel's answer上的一个变体,它将原始实体重新用于新列表而不是克隆它们:
List<Entities.Base> bases = this.GetAllBases();
List<Entities.Base> thebases = new List<Entities.Base>(
from aBase in bases
where aBase.OfficeCD == officeCD
select aBase);