tags:

views:

105

answers:

3

I am squaring each integer in a List. Here is the code.

class SomeIntgs
{
    List<int> newList = new List<int>();

    public List<int> get()
    {
        IEnumerable<int> intrs = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
        newList.AddRange(intrs);
        return newList;

    }
}

I am getting error in Main()

    SomeIntgs stg = new SomeIntgs();
    var qry = from n in stg.get() where (P => P*P) select n;

Error : "Can not convert lambda expression to type bool ".

Help Please.

Also help me, how can i handle lambda in general context

+6  A: 

You don't need the where, try this:

SomeIntgs stg = new SomeIntgs();
var qry = from n in stg.get() select n*n;

or

var qry = stg.get().Select(P => P*P);

Enumerable.Where is used to filter elements from a sequence - what you really want to do is project a new sequence of elements like I have shown above.

Andrew Hare
I haven't seen any linq query with a lambda expression like that, won't that fail as well?
eglasius
I am receiving error as"The typeof the expression in the select clause is incorrect"
@russeludana ... try mine, as I mentioned before, that's v. weird for a linq query, I think that is just wrong ...
eglasius
There was just some confusion over which syntax was in use. :) I fixed it.
280Z28
@280Z28 - That's what I get for posting without testing - thanks! :)
Andrew Hare
+3  A: 
SomeIntgs stg = new SomeIntgs();
var qry = from n in stg.get() select n*n;
eglasius
I am quite particular about applying lambda here.
@russeludana u don't need lambda there, perhaps you should explain more specifically what u want to achieve?
eglasius
+3  A: 

The lambda that the where clause takes specifies how you match an item from your IQueryable. Any member of the IQueryable that satisfies the expression you supply will be returned. (This is why your compiler is complaining about bools).

As others have mentioned, you can drop the where clause to square each item in the list.

var ints = new int []{1,2,3,4,5,6,7,8};
var squares = ints.Select(x => x*x);
var evenSquares = ints.Where(x => (x % 2) == 0).Select(x => x*x); // only square 
                                                     //the even numbers in the list
Kirschstein
I am getting error when i go for var evensquares=from even in stg.get().Where(x=>(x%2)==0).Select(x=>x*x); Error :A Query must be end with select clause or group clause
I found the solution the form clause expects select.I got it and changed my coe.Thanks Kris