LINQ Cast List a list of a specific type.

I am trying to formulate a LINQ query to select a list sublist where it encounters such a condition:

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

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

I get the error "Unable to substitute a conversion of type System.Collections.Generic.IEnumerable to System.Collections.Generic.List

So, I tried to apply the Cast operator, but that fails. Now I see that I am not trying to convert the element type. How can I solve this problem? Thank!

+5
source share
3 answers

, ""; , , - , . 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);
+10

@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

Here's a Joel answer option that reuses the source objects for a new list instead of cloning them:

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

All Articles