JBone
JBone

Reputation: 3203

Linq into object

Is there a way to run a linq query into a predefined or custom class all in the query without having to perform extra operations outside?

class Numbers {
  int number
  bool even
}

...populate numbers class

List<Numbers> bigNumbers = (
    from n in numbers
    where n.number >= 1000000
    select n)

The following throws a conversion error.

Upvotes: 0

Views: 133

Answers (4)

richk
richk

Reputation: 416

Something like this?

List<Numbers> bigNumbers = numbers.Where(w => w.number >= 1000000).ToList();

Upvotes: 1

mgnoonan
mgnoonan

Reputation: 7200

You are close. You have created a Linq query, but you are trying to assign the query to a List<Numbers> variable. You need to add .ToList() at the end.

List<Numbers> bigNumbers = (
     from n in numbers
     where n.number >= 1000000
     select n).ToList();

Upvotes: 0

Kendall Frey
Kendall Frey

Reputation: 44316

You need to call ToList if you really want it in a List.

List<Numbers> bigNumbers = (
    from n in numbers
    where n.number >= 1000000
    select n)
    .ToList();

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160852

You are missing a ToList():

List<Numbers> bigNumbers = (
    from n in numbers
    where n.number >= 1000000
    select n).ToList();

Upvotes: 5

Related Questions