开发者

LINQ list of sublist

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


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 :)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜