开发者

what's difference in given LINQ to collection query?

I am pretty confused in collection and IEnumerable types. Can any one explain why the 1st query is wrong but the 2nd is correct-

1st- this gives error

ConditionFieldCollection conditionColl = (ConditionFieldCollection)Session["ConditionFieldCollection"];
ConditionFieldCollection cnd = new ConditionFieldCollection(); 
cnd = (from c in conditionColl
            where iq.QueryField == c.Expression
                select c);

2nd - works fine

ConditionFieldCollection conditionColl = (ConditionFieldCollection)Session["ConditionFieldCollection"];
List<ConditionField> cnd = (from c in conditionColl.OfType<ConditionField>()
                                       where iq.QueryField == c.Expression
                                       select c).ToList();

I know LINQ returns IEnumerable type of collection object but ConditionFieldCollection is also a Collection then why it gives me error at compile time. Is there any difference b/w Collecton and IEnumerable Collecti开发者_Go百科on??


You are attempting to assign an IEnumerable<ConditionField> to a variable with type ConditionFieldCollection - that can't work. An enumerable is not a collection, and certainly isn't that specific collection.

Many collections allow an enumerable constructor, so this may work:

ConditionFieldCollection cnd = new ConditionFieldCollection(
    from c in conditionColl
    where iq.QueryField == c.Expression
    select c);


Just because ConditionFieldCollection is a collection does not mean it is the same collection as the return value from the query.

It is like saying

class Mammal{}
class Dog : Mammal {}
class Cat : Mammal {}

Dog d = new Dog();
Cat c = new Cat();
d = c; // Wrong, even though they are both mammals they are not the same kind of mammal.

Edit
Depending on how ConditionFieldCollection works you may have two options, hopefully at least one of them works.

1

ConditionFieldCollection cnd = new ConditionFieldCollection(); 
cnd.AddRange(from c in conditionColl
             where iq.QueryField == c.Expression
             select c);

2

ConditionFieldCollection cnd = 
    new ConditionFieldCollection(from c in conditionColl
                                 where iq.QueryField == c.Expression
                                 select c);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜