[英]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 :) PS:在第三次尝试:)
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子句修改为
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). IEnumarable<T>
具有的扩展方法OfType<>
当你想限制选择给定类型,如果有一个排除选择(或者,如果有,我不知道它这将是很好,这将是有益的)。 If there were, you could use that on f.Bar and eliminate the where clause. 如果有的话,可以在f.Bar上使用它,并消除where子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.