开发者

how to add default element in sequence if is empty? using DefaultIfEmpty()

i have query that maybe haven't any element on sequence and i want to add one element to sequence if is empty.

var results = _context.Documents.Select(document => document.MimeType).Distinct().ToList().DefaultIfEmpty("There is nothing to be used as MimeType");

b开发者_StackOverflow社区ut still sequence is empty however is used DefaultIfEmpty method.


Yes, you can use DefaultIfEmpty() for this purpose. (However, note that the ToList() in your query is redundant.)

For example:

string[] s1 = new string[] { };
string[] s2 = new string[] { "abc" };

// Outputs "DEFAULT" because the sequence s1 is empty.
foreach (var s in s1.DefaultIfEmpty("DEFAULT"))
    Console.WriteLine(s);

// Outputs "abc" from the sequence s2 and nothing else.
foreach (var s in s2.DefaultIfEmpty("DEFAULT"))
    Console.WriteLine(s);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜