Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Have you considered using LINQ's <a href="http://msdn.microsoft.com/en-us/library/bb360913.aspx" rel="nofollow noreferrer">OfType</a> extension method? It wraps an enumerable and filters the elements so that only the ones of the specified type are returned. You could use it like this:</p> <pre><code>list.AddRange(superList.OfType(Of SubClass)()) </code></pre> <p>or even:</p> <pre><code>list = superList.OfType(Of SubClass)().ToList() </code></pre> <p>Sorry if my syntax is off, it's been a while since I've used VB.NET</p> <hr> <p><strong>Edit:</strong> Example, as promised:</p> <pre><code>namespace Demo.ListFilter { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; class Program { private class SuperClass { } private class SubClassA : SuperClass { } private class SubClassB : SuperClass { } static void Main(string[] args) { var superList = new List&lt;SuperClass&gt;() { new SuperClass(), new SuperClass(), new SuperClass(), new SuperClass(), new SubClassA(), new SubClassA(), new SubClassA(), new SubClassB(), new SubClassB(), new SubClassB(), new SubClassB() }; var listA = new List&lt;SubClassA&gt;(); var listB = new List&lt;SubClassB&gt;(); SplitList(superList, listA, listB); Console.WriteLine("List A: {0}", listA.Count); Console.WriteLine("List B: {0}", listB.Count); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } static void SplitList(IList superList, params IList[] subLists) { foreach(var subList in subLists) { var type = subList.GetType().GetGenericArguments()[0]; FilterList(superList, subList, type); } } static void FilterList(IList superList, IList subList, Type type) { var ofTypeMethod = typeof(Enumerable).GetMethod("OfType"); var genericMethod = ofTypeMethod.MakeGenericMethod(type); var enumerable = (IEnumerable)genericMethod.Invoke(null, new[] { superList }); foreach(var item in enumerable) { subList.Add(item); } } } } </code></pre> <hr> <p><strong>Another Edit:</strong> You could also combine the methods like this:</p> <pre><code> static void SplitList(IList superList, params IList[] subLists) { var ofTypeMethod = typeof(Enumerable).GetMethod("OfType"); foreach(var subList in subLists) { var subListType = subList.GetType(); var type = subListType.GetGenericArguments()[0]; var genericOfTypeMethod = ofTypeMethod.MakeGenericMethod(type); var enumerable = genericOfTypeMethod.Invoke(null, new[] { superList }); var addRangeMethod = subListType.GetMethod("AddRange"); addRangeMethod.Invoke(subList, new[] { enumerable }); } } </code></pre> <p><em>Don't forget to add error handling!</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload