In C# linq, is there a difference between A.where(...)
and A.where<SomeClass>(...)
where A
is some type of suitable collection?
在C#linq中,A.where(...)和A.where
1 个解决方案
#1
In general no, because the compiler will infer the type T
of the IEnumerable<>
A
and use as the generic parameter of the .Where<>()
通常不会,因为编译器会推断IEnumerable <> A的类型T并用作.Where <>()的泛型参数
but
You could force the Where<>
to "use" a SomeClass
that is a base class of the T
type of the IEnumerable<>
(this works because IEnumerable<>
is covariant, so IEnumerable<subclass>
can be "casted" to IEnumerable<baseclass>
)...
你可以强制Where <>“使用”一个SomeClass,它是IEnumerable <>的T类型的基类(这是因为IEnumerable <>是协变的,所以IEnumerable
The only practical result would be that you would "see" in the Where()
a little "less" of T
(and that if there are properties/methods of T
that are "overwritten" by SomeClass
you will access them without having to do casts)
唯一可行的结果是你会在Where()中“看到”一点“少”的T(并且如果T的属性/方法被SomeClass“覆盖”,你将无需访问它们铸)
Example:
public class MyClass
{
public int GetNumber()
{
return 1;
}
}
public class MySubClass : MyClass
{
// Note the use of *new*. This isn't a virtual method!
public new int GetNumber()
{
return 2;
}
}
MySubClass[] coll = new[] { new MySubClass(), new MySubClass() };
var res = coll.Where(x => x.GetNumber() == 2).ToArray(); // 2 elements
var res2 = coll.Where<MyClass>(x => x.GetNumber() == 2).ToArray(); // 0 elements
var res3 = coll.Where<MyClass>(x => x.GetNumber() == 1).ToArray(); // 2 elements
#1
In general no, because the compiler will infer the type T
of the IEnumerable<>
A
and use as the generic parameter of the .Where<>()
通常不会,因为编译器会推断IEnumerable <> A的类型T并用作.Where <>()的泛型参数
but
You could force the Where<>
to "use" a SomeClass
that is a base class of the T
type of the IEnumerable<>
(this works because IEnumerable<>
is covariant, so IEnumerable<subclass>
can be "casted" to IEnumerable<baseclass>
)...
你可以强制Where <>“使用”一个SomeClass,它是IEnumerable <>的T类型的基类(这是因为IEnumerable <>是协变的,所以IEnumerable
The only practical result would be that you would "see" in the Where()
a little "less" of T
(and that if there are properties/methods of T
that are "overwritten" by SomeClass
you will access them without having to do casts)
唯一可行的结果是你会在Where()中“看到”一点“少”的T(并且如果T的属性/方法被SomeClass“覆盖”,你将无需访问它们铸)
Example:
public class MyClass
{
public int GetNumber()
{
return 1;
}
}
public class MySubClass : MyClass
{
// Note the use of *new*. This isn't a virtual method!
public new int GetNumber()
{
return 2;
}
}
MySubClass[] coll = new[] { new MySubClass(), new MySubClass() };
var res = coll.Where(x => x.GetNumber() == 2).ToArray(); // 2 elements
var res2 = coll.Where<MyClass>(x => x.GetNumber() == 2).ToArray(); // 0 elements
var res3 = coll.Where<MyClass>(x => x.GetNumber() == 1).ToArray(); // 2 elements