473,903 Members | 3,829 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert from List<A> to List<B>

Hi,

Have class B which subclasses from class A. I have a List<B> and I'm
trying to get a List<A> without writing a stupid loop everytime I want
to do it. So I tried this method:

public static List<Destinatio n> ConvertList<Sou rce,
Destination>(Li st<Source> sourceList) where Destination : Source
{
List<Destinatio n> result = new List<Destinatio n>();
foreach (Source aSource in sourceList)
{
result.Add(aSou rce as Destination);
}
return result;
}

It didn't work, is it possible?

Why isn't there a method like this:
List<B> aList = new List<B>();
List<A> newList = aList.Convert<A >();

Any ideas?

Thanks,

Jun 20 '06 #1
4 17168
Like so?

List<B> aList = new List<B>();
List<A> newList = aList.ConvertAl l<A>(delegate( B item) {return (A) (object)
item;});

The (object) cast is needed where an explicit cast operator is not provided
by the class - or you could build the replacement objects yourself.

Marc
Jun 20 '06 #2
Additional: I didn't spot the "B subclasses A"; this means you can drop the
(object) cast

Finally - is this so you can can pass a List<A> as method parameters? If so,
note that this is a covariance issue, and can be resolved through generics
(see Right() below)

Marc

static void Main() {
List<B> aList = new List<B>();
List<A> newList = aList.ConvertAl l<A>(delegate( B item) { return
(A)item; });

Wrong(aList);
Right(aList);
}
public static void Wrong(List<A> items) {
//do stuff with each A
}
public static void Right<T>(List<T > items) where T : A{
//do stuff with each T, which can also be treated as A
}
public class A { }
public class B : A { }
Jun 20 '06 #3
That looks OK. How was it failing?

bo**********@ho tmail.com wrote:
Have class B which subclasses from class A. I have a List<B> and I'm
trying to get a List<A> without writing a stupid loop everytime I want
to do it. So I tried this method:
[snip]
It didn't work, is it possible?


Jun 20 '06 #4
<bo**********@h otmail.com> wrote in message
news:11******** **************@ b68g2000cwa.goo glegroups.com.. .
Hi,

Have class B which subclasses from class A. I have a List<B> and I'm
trying to get a List<A> without writing a stupid loop everytime I want
to do it. So I tried this method:

public static List<Destinatio n> ConvertList<Sou rce,
Destination>(Li st<Source> sourceList) where Destination : Source
{
List<Destinatio n> result = new List<Destinatio n>();
foreach (Source aSource in sourceList)
{
result.Add(aSou rce as Destination);
}
return result;
}

It didn't work, is it possible?


If you reverse the where constraint, this works:

public static List<Destinatio n> ConvertList<Sou rce,
Destination>(Li st<Source> sourceList)
where Source : Destination
{
List<Destinatio n> result = new List<Destinatio n>();

foreach (Source aSource in sourceList)
result.Add(aSou rce);

return result;
}

///ark
Jun 20 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
6902
by: Michael | last post by:
This is a two-part question to which I haven't been able to find an answer anywhere else. 1. Is it possible to format the bullet/number character of the <li>? In my styles sheet, I have the <li> tag formatted, for example, bold. However, when it's applied, the number of the <li> is not bold, but the text is. Do I have to apply the bold to the <ol> instead? 2. When I use <li>example text</li>, and when I insert a <br> after the </li>,...
1
1779
by: Alex Nitulescu | last post by:
Hi. Something puzzles me: VS.NET says that "per the active schema, li cannot be nested within td". However, the code works fine, and the result is as I expected. Is there something wrong in disregarding that warning ?? Also, no matter what I do, VS.NET always *INSISTS* to change my <tr valign = middle> to <tr valign = center>... Of course, after changing it, it complains that "The values permitted for this attribute do not include...
4
3047
by: David Lozzi | last post by:
Howdy, I'm using a WYSIWYG editor called TinyMCE. When I edit some text and then save it back to my SQL server using a SQLCommand, all HTML characters are changed to HTML code, i.e. &gt;strong&lt; instead of <strong> and so on. Is this a problem with the editor or something else? Does .Net convert it? I had to disable page validate request because of the tags, is there more? Thanks,
5
75370
by: Andrew Robinson | last post by:
Any easy answer what is wrong here? private List<string> BodyWords = new List<string>(); string word = "Andrew"; the following causes a compilation error:
7
5109
by: mark | last post by:
Hi All, Apologies for the newbie question but I've searched and tried all sorts for a few days and I'm pulling my hair out ; Please feel free to teach me to suck eggs because it's all new to me :) Thanks in advance, Mark.
5
3844
by: David Longnecker | last post by:
I'm working to create a base framework for our organization for web and client-side applications. The framework interfaces with several of our systems and provides the business and data layer connectivity for basic operations and such. I've ran into a snag that I just can't think myself out of. Here's an example: I have an object for a Student called StudentRecord. It has properties such as name, grade, identification number, etc.
2
2068
by: -Karl | last post by:
Couls someone please advise me on this error. What I am trying to do is be able to convert an XML document into arrays. I read that the subs & functions have to be in <scripttags. Thanks! Error: BC30456: 'Read_DOM' is not a member of
1
8879
by: shapper | last post by:
Hello, On my MVC projects I often create classes which contains properties which are lists of other classes. Should I start using IQueryable<Tor IEnumerable<Tinstead of List<T>? What are the differences and when should I use IQueryable<T>, IEnumerable<Tor List<T>?
2
2369
by: Shahid | last post by:
Hi, I am parsing an .HTML file that contains following example code: <div> <p class="html_preformatted" awml:style="HTML Preformatted" dir="ltr" style="text-align:left"><span style="font-size:12pt;font- family:'Arial'" xml:lang="en-US" lang="en-US">Normal Text Arial 12 Black before bullets.</span></p> <ul> <li class="html_preformatted" dir="ltr" style="text- align:left">&nbsp;<span style="font-size:12pt;font-family:'Arial'"
2
4975
by: Berryl Hesh | last post by:
Converting in the other direction , IEnumerable<Interfaceto List<ImplInterface>, I can just create a new List<ImplInterface(data) where data is IEnumerable<Interface>. How can I convert the List<ImplInterfaceto IEnumerable<Interface>? Thanks, BH
0
10004
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10504
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9692
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7215
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5899
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6100
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4734
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4315
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3327
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.