1
我有一个相册任务,我需要显示来自数据库的图像。假设数据库中没有匹配的图像,我可以使用DefaultIfEmpty
来选择默认图像吗?我们可以使用DefaultIfEmpty显示默认图像吗?
我有一个相册任务,我需要显示来自数据库的图像。假设数据库中没有匹配的图像,我可以使用DefaultIfEmpty
来选择默认图像吗?我们可以使用DefaultIfEmpty显示默认图像吗?
编辑:DefaultIfEmpty
已经有一个合适的过载。
你不能提供一个默认值FirstOrDefault()
,但你总是可以使用:
// Select the first image, or a default otherwise
var image = query.FirstOrDefault() ?? defaultImage;
或者你也可以写自己的FirstOrDefault
超负荷其中不接受默认的,当然。类似这样的:
public static T FirstOrDefault<T>(this IEnumerable<T> source,
T defaultValue)
{
// This will only ever iterate once, of course.
foreach (T item in source)
{
return item;
}
return defaultValue;
}
为什么在这里不能使用DefaultIfEmpty?不是DefaultIfEmpty已经有超载? – nawfal 2012-11-02 13:31:15