tags:

views:

79

answers:

2

I'm trying to get all the sublists that don't inherit from a specified class and also get the parent/root list type. I can't quite figure out the syntax. Here's an example of the sort of thing I'm looking for. Thanks for any help you can give!

public class Foo
{
  public IList<Type> Bar { get; private set; }
}

List<Foo> test = new List<Foo>();
// Initialize, add values, etc.

var result = from f in test
             from b in f.Bar
             where !b.IsSubclassOf(typeof(AnotherClass))
             select f.GetType(), b
+1  A: 

Maybe something like this:

  var result = test.SelectAll(i => i.Bar).Where(i => !(i is AnotherClass)).Select(i => new { Type = i.GetType(), Item = i});

PS: at the 3rd attempt :)

Nagg
Not quite... I need to select f.GetType(), not i.GetType(). Even though Anthony did the same thing, it's easier to change his. :)
Nelson
A: 

Is this what you're looking for?

class Foo
{
    public IList<object> Bar { get; set; }
}

...

Foo foo = new Foo();
foo.Bar = new List<object>();
foo.Bar.Add(1);
foo.Bar.Add("a");

Foo foo2 = new Foo();
foo2.Bar = new List<object>();
foo2.Bar.Add(2);
foo2.Bar.Add('b');

List<Foo> foos = new List<Foo>() { foo, foo2 };

var query = from f in foos
            from b in f.Bar
            where !(b is string)
            select new
            {
                InnerObjectType = b.GetType(),
                InnerObject = b
            };

foreach (var obj in query)
    Console.WriteLine("{0}\t{1}", obj.InnerObjectType, obj.InnerObject);

Edit: If the type to exclude was a parameter, you could modify the where clause to be

where b.GetType() != type

IEnumarable<T> has an extension method of OfType<> that would be useful when you want to limit selection to a given type, it would be nice if there was an exclusionary alternative (or if there is, I don't know of it). If there were, you could use that on f.Bar and eliminate the where clause.

Anthony Pegram
Close, but instead of InnerObjectType it should be OuterObjectType = f.GetType(). Also, I don't want it to match the base class, only derived classes, so I have to do the IsSubclassOf(), but that's a non-LINQ detail. I was missing the new {}
Nelson