當前位置: 首頁>>代碼示例>>C#>>正文


C# Queryable.DefaultIfEmpty方法代碼示例

本文整理匯總了C#中System.Linq.Queryable.DefaultIfEmpty方法的典型用法代碼示例。如果您正苦於以下問題:C# Queryable.DefaultIfEmpty方法的具體用法?C# Queryable.DefaultIfEmpty怎麽用?C# Queryable.DefaultIfEmpty使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。


在下文中一共展示了Queryable.DefaultIfEmpty方法的2個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: DefaultIfEmptyEx1

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void DefaultIfEmptyEx1()
{
    // Create a list of Pet objects.
    List<Pet> pets =
        new List<Pet>{ new Pet { Name="Barley", Age=8 },
                       new Pet { Name="Boots", Age=4 },
                       new Pet { Name="Whiskers", Age=1 } };

    // Call DefaultIfEmtpy() on the collection that Select()
    // returns, so that if the initial list is empty, there
    // will always be at least one item in the returned array.
    string[] names =
        pets.AsQueryable()
        .Select(pet => pet.Name)
        .DefaultIfEmpty()
        .ToArray();

    string first = names[0];
    Console.WriteLine(first);
}
開發者ID:.NET開發者,項目名稱:System.Linq,代碼行數:26,代碼來源:Queryable.DefaultIfEmpty

輸出:

Barley

示例2: catch

// Create a list of Pet objects.
    List<Pet> pets =
        new List<Pet>{ new Pet { Name="Barley", Age=8 },
                       new Pet { Name="Boots", Age=4 },
                       new Pet { Name="Whiskers", Age=1 } };

    // This query selects only those pets that are 10 or older.
    // In case there are no pets that meet that criteria, call
    // DefaultIfEmpty(). This code passes an (optional) default
    // value to DefaultIfEmpty().
    string[] oldPets =
        pets.AsQueryable()
        .Where(pet => pet.Age >= 10)
        .Select(pet => pet.Name)
        .DefaultIfEmpty("[EMPTY]")
        .ToArray();

    Console.WriteLine("First query: " + oldPets[0]);

    // This query selects only those pets that are 10 or older.
    // This code does not call DefaultIfEmpty().
    string[] oldPets2 =
        pets.AsQueryable()
        .Where(pet => pet.Age >= 10)
        .Select(pet => pet.Name)
        .ToArray();

    // There may be no elements in the array, so directly
    // accessing element 0 may throw an exception.
    try
    {
        Console.WriteLine("Second query: " + oldPets2[0]);
    }
    catch (Exception e)
    {
        Console.WriteLine("Second query: An exception was thrown: " + e.Message);
    }
開發者ID:.NET開發者,項目名稱:System.Linq,代碼行數:37,代碼來源:Queryable.DefaultIfEmpty

輸出:

First query: [EMPTY]
        Second query: An exception was thrown: Index was outside the bounds of the array.


注:本文中的System.Linq.Queryable.DefaultIfEmpty方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。