LINQ Cast可枚举为特定类型的列表 [英] LINQ Cast Enumerable to List of specific type

查看:87
本文介绍了LINQ Cast可枚举为特定类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制定一个LINQ查询,以选择满足以下条件的列表的子列表:

I am trying to formulate a LINQ query to select a sublist of a list where it meets a where condition like so:

List<Entities.Base> bases = this.GetAllBases();
List<Entities.Base> thebases = from aBase in bases
                               where aBase.OfficeCD == officeCD
                               select aBase;

其中Base只是一个实体类:

where Base is just an Entity class:

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

I am getting an error "Cannot implictly convert type System.Collections.Generic.IEnumerable to System.Collections.Generic.List

所以我尝试应用Cast运算符,但是失败了.现在,我知道我不打算转换该元素的类型.我该如何解决这个问题?谢谢!

So I tried to apply the Cast operator but that fails. I see now that I am not tring to convert the type of the element. How can I solve this issue? Thanks!

推荐答案

这不是可以通过广播"解决的问题.您所查询的结果不是列表-这是一个延迟执行的序列,该序列将按需 流出匹配项.您实际上必须将这些结果加载到List<T>中才能实现您的目的.例如,Enumerable.ToList方法将创建一个新列表,将查询结果填充到该列表中,然后将其返回.

This is not really a problem that can be solved by "casting"; the result of the query you've got isn't a list - it's a deferred-executing sequence that will stream the matching items out on demand. You will have to actually load these results into aList<T>to achieve your purpose. For example, the Enumerable.ToListmethod will create a new list, populate it with the results of the query and then return it.

一些选项:

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);

这篇关于LINQ Cast可枚举为特定类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆