本文整理匯總了C#中System.Linq.Enumerable.DefaultIfEmpty方法的典型用法代碼示例。如果您正苦於以下問題:C# Enumerable.DefaultIfEmpty方法的具體用法?C# Enumerable.DefaultIfEmpty怎麽用?C# Enumerable.DefaultIfEmpty使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。
在下文中一共展示了Enumerable.DefaultIfEmpty方法的4個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: DefaultIfEmptyEx2
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void DefaultIfEmptyEx2()
{
Pet defaultPet = new Pet { Name = "Default Pet", Age = 0 };
List<Pet> pets1 =
new List<Pet>{ new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
foreach (Pet pet in pets1.DefaultIfEmpty(defaultPet))
{
Console.WriteLine("Name: {0}", pet.Name);
}
List<Pet> pets2 = new List<Pet>();
foreach (Pet pet in pets2.DefaultIfEmpty(defaultPet))
{
Console.WriteLine("\nName: {0}", pet.Name);
}
}
輸出:
Name: Barley Name: Boots Name: Whiskers Name: Default Pet
示例2: DefaultIfEmptyEx1
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void DefaultIfEmptyEx1()
{
List<Pet> pets =
new List<Pet>{ new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
foreach (Pet pet in pets.DefaultIfEmpty())
{
Console.WriteLine(pet.Name);
}
}
輸出:
Barley Boots Whiskers
示例3: foreach
List<int> numbers = new List<int>();
foreach (int number in numbers.DefaultIfEmpty())
{
Console.WriteLine(number);
}
輸出:
0
示例4: Main
//引入命名空間
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] presidents = {"G", "H", "a", "H", "over", "Jack"};
string name =
presidents.Where(n => n.Equals("H")).DefaultIfEmpty("Missing").First(); Console.WriteLine(name);
}
}