1

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

asked Oct 19, 2009 at 16:44

3 Answers 3

7

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.

Sam Harwell
100k22 gold badges216 silver badges283 bronze badges
answered Oct 19, 2009 at 16:46
Sign up to request clarification or add additional context in comments.

5 Comments

I haven't seen any linq query with a lambda expression like that, won't that fail as well?
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 ...
There was just some confusion over which syntax was in use. :) I fixed it.
@280Z28 - That's what I get for posting without testing - thanks! :)
4

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
answered Oct 19, 2009 at 16:55

2 Comments

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
3
SomeIntgs stg = new SomeIntgs();
var qry = from n in stg.get() select n*n;
answered Oct 19, 2009 at 16:49

2 Comments

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?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.