GeeksforGeeks App
Open App
Browser
Continue

# C# Program to Find the Negative Double Numbers From the List of Objects Using LINQ

Given a list of objects, we need to find the negative double from the list of objects, this task can be done using the OfType() method along with the Where() method. OfType() method is used to filter the elements of an IEnumerable based on a specified type. Or in other words, this method is used to filter the list or sequence source depending upon their ability to cast an item in a collection to a specified type. It will throw an ArgumentNullException if the given source is null.

Syntax:

public static System.Collections.Generic.IEnumerable<TResult> OfType<TResult>(this System.Collections.IEnumerable source);

Where() method is used to filter the value based on the predicate function. Or we can say that it returns the values from the given sequence or list according to the given condition or criteria.

Syntax:

Where<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

Example:

```Input  : ["sai", 100, "mohan", -18.0, -30.2, 200, "rajesh"]
Output : [-18.0, -32.2]

Input  : ["raju", -345.0, 18.3 , "mohan", -18.0, 193, -30.2, 200, "rajesh"]
Output : [-345.0, -18.0, -32.2]```

Approach:

• Create an list of objects.
`List<object> objList = new List<object>()`
• Now using the OfType<double>() method and the Where() method select the double values which are less than zero i.e. negative double numbers.
`List<double> result = objList.OfType<double>().Where(n => n < 0).ToList();`
• Print the negative double numbers using the foreach loop.
```foreach (double negative in result)
{
Console.Write(negative + "  ");
} ```

## C#

 `// C# program to find the negative double``// numbers from the given list of objects``using` `System;``using` `System.Linq;``using` `System.Collections.Generic;`` ` `class` `GFG{`` ` `static` `void` `Main(``string``[] args)``{``     ` `    ``// Creating and initialize the list of object``    ``List<``object``> objList = ``new` `List<``object``>(){``    ``"raju"``, -345.0, 18.3 , ``"mohan"``, -18.0,``    ``193, -30.2, 200, ``"rajesh"` `};`` ` `    ``// Filtering the negative double objects``    ``// from objList and convert to list``    ``List<``double``> result = objList.OfType<``double``>().Where(n => n < 0).ToList();`` ` `    ``// Display the output list``    ``Console.Write(``"Negative numbers are:"``);``    ``foreach` `(``double` `negative ``in` `result)``    ``{``        ``Console.Write(negative + ``"  "``);``    ``}``}``}`

Output:

`Negative numbers are:-345  -18  -30.2  `
My Personal Notes arrow_drop_up