Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering Null values in Select

Tags:

linq

I have IQueryable list of objects of type T which I want to transform into objects of type K

List<K> tranformedList = originalList.Select(x => transform(x)).ToList();

the transform function returns null if it cannot tranform the objects.If I want to filter out null elements can I call

List<K> tranformedList = originalList.Select(x => transform(x))
                                     .Where(y => y != default(K))
                                     .ToList();

or is there any other way of filtering out null elements when calling Select in LINQ ?

like image 541
fatbuddha Avatar asked Dec 31 '08 00:12

fatbuddha


People also ask

How do you filter NULL values?

After creating the formula for what you want to do, you can filter on the formula column you created in the search bar by typing the value {blank}, {empty}, or {null}, which will act as a filter. Then, you can type normal filter syntax, such as customer name = {empty} or department != {null} .

How do I avoid NULL values in select query?

SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator.

How do you filter NULL values in filter transformation?

To filter out rows containing null values or spaces, use the ISNULL and IS_SPACES functions to test the value of the port. want. create two targets like t1,t2. Filter will drop those rows which have NULL or Spaces value for ename field.


2 Answers

Can't you just do something like this:

List<K> tranformedList = originalList.Select(x => tranform(x))
                                 .Where(y => y != null) //Check for nulls
                                 .ToList();
like image 147
Nathan W Avatar answered Sep 21 '22 11:09

Nathan W


What about

    List<K> tranformedList = originalList
                             .Select(transform)
                             .OfType<K>()
                             .ToList()

Takes care of unboxing an getting rid of nulls at the same time (especially when K is a struct)

David B I dont believe you that your code .Where(y => y != null) works when K is an int! There is NO WAY you will get that code to compile if K is an int!

like image 70
stitty Avatar answered Sep 17 '22 11:09

stitty