0

I have two classes:

public class Article : IPosition    
public class AssemblyGroup : IPosition

I have a List<IPosition> positions where I have items from both classes as ItemsSource for my view. Now I want to retreive the different objects like

var articlePositions = positions.Where(all Article objects)
var assemblyGroupPositions = positions.Where(all AssemblyGroup objects)

Is there any other way other than a foreach loop and adding every item of the list to another list?

Thank you.

  • Yeah you should be using OfType<> – johnny 5 Feb 10 '21 at 14:54
  • Take a look at https://stackoverflow.com/questions/1159906 . Your question sounds a bit like it's defeating the purpose of using an `interface`. – Nate W Feb 10 '21 at 14:55
  • 1
    why do you keep them in a single collection in the first place? – Mong Zhu Feb 10 '21 at 14:58
  • @NateW I need those two when I want to save some changes. As my database needs the specific class type I need to split my interface. Everything else works with the interface. Thank you for the link and the additional info. – LiliumCandidum Feb 10 '21 at 15:02
  • 1
    Consider adding a method to your interface `Save()`. Then, each individual implementation of the interface or object repository can handle saving it, rather than the class that's calling the interface. – Nate W Feb 10 '21 at 15:07
  • @NateW Thank you, I will try it with a save method in my interface. – LiliumCandidum Feb 10 '21 at 15:12
  • @MongZhu I have two different types that can be a position. As the two types are saved in two different tables in my database, I had to implement the interface to show both in one list for my position view. – LiliumCandidum Feb 10 '21 at 15:15

1 Answers1

1

Yeah you should be using OfType<> which will grab only the things of that type.

positions.OfType<Article>()
positions.OfType<AssemblyGroup>()
johnny 5
  • 19,893
  • 50
  • 121
  • 195