C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: This program uses Where to filter out null and empty strings in a declarative method call style.
Array: We see a string array that contains some null and empty strings. The Where() eliminates the null and empty strings.
Note: The first Where call specifies that only non-null items should be kept. The second Where method call uses IsNullOrEmpty.
IsNullOrEmpty, IsNullOrWhiteSpaceC# program that uses Where method
using System;
using System.Linq;
class Program
{
static void Main()
{
//
// Example array that contains unwanted null and empty strings.
//
string[] array = { "dot", "", "net", null, null, "Codex", null };
//
// Use Where method to remove null strings.
//
var result1 = array.Where(item => item != null);
foreach (string value in result1)
{
Console.WriteLine(value);
}
//
// Use Where method to remove null and empty strings.
//
var result2 = array.Where(item => !string.IsNullOrEmpty(item));
foreach (string value in result2)
{
Console.WriteLine(value);
}
}
}
Output
dot
net
Codex
dot
net
Codex
C# program that uses where
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40 };
// ... Filter numbers with where.
var result = from number in numbers
where number >= 30
select number;
// ... Display results.
foreach (int value in result)
{
Console.WriteLine(value);
}
}
}
Output
30
40
Tip: Here we create a generic type called PageSet that can act on any element that implements the IPage interface.
Tip 2: We can use PageSet for any class that implements IPage—only one generic implementation is needed (this is a key advantage).
Also: More information is available about type constraints and generic types, and information about closed and open types.
Generic Class, MethodC# program that uses where constraint keyword
using System;
using System.Collections.Generic;
/// <summary>
/// PageSet (could be set of anything that implements IPage).
/// </summary>
class PageSet<T> where T : IPage
{
List<T> _pages = new List<T>();
public void Add(T page)
{
_pages.Add(page);
}
public void Render()
{
foreach (T page in _pages)
{
page.Render();
}
}
}
/// <summary>
/// IPage.
/// </summary>
interface IPage
{
void Render();
}
/// <summary>
/// ImagePage (implements IPage).
/// </summary>
class ImagePage : IPage
{
public void Render()
{
Console.WriteLine("Render ImagePage");
}
}
class Program
{
static void Main()
{
// ... Create a generic type with constraint.
PageSet<ImagePage> pages = new PageSet<ImagePage>();
// ... Add an instance to the generic type.
ImagePage image = new ImagePage();
pages.Add(image);
// ... Use the generic type.
pages.Render();
}
}
Output
Render ImagePage
Note: Thanks to Andrew Steitz for writing in with a correction to a program that uses the where keyword for a type constraint.