简体   繁体   中英

C# list conversion in asp.net

I have a business object class BusinessObject which implements an interface IAlternateInterface. I already have a method that will return a generic list of BusinessObject which has the objects I want but I want to get them as a list of IAlternateInterface. I tried to do something like the following psudo code but I am getting a "Can not convert source type ... to target type ..." message in Visual Studio. What is the best way to convert the list?

public List<BusinessObject> GetObjects(){
 //logic to get the list
}

public List<IAlternateInterface> GetInterfaceObjects(){
 return GetObjects();
}

You're looking for Enumerable.Cast<TResult> :

GetObjects().Cast<IAlternateInterface>.ToList();

The ToList at the end is only necessary if you need a list. Cast<TResult> returns an IEnumerable<TResult>

The two answers given using Cast are fine for C# 3 and C# 4... but if you're using C# 4 (and .NET 4) you can also use generic variance to avoid one step:

public List<IAlternateInterface> GetInterfaceObjects(){
  return GetObjects().ToList<IAlternateInterface>();
}

With LINQ Cast

public List<IAlternateInterface> GetInterfaceObjects(){
 return GetObjects().Cast<IAlternateInterface>().ToList();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM