Mã:
var query=(
from role in roleList
let delimiter=WorkflowConstants.WorkflowRoleDelimiter
let roleArray=role.RoleId.Split(new char[] { delimiter })
where roleArray.Length.Equals(_SplittedRoleIdArrayLength)
where HasAccessToCurrentUnit(roleArray[_UnitIndexInRoleId])
select roleArray[_LevelIndexInRoleId]
).DefaultIfEmpty("").FirstOrDefault();
Đối với sự nghi ngờ về ý nghĩa ngữ nghĩa của DefaultIfEmpty
và FirstOrDefault
, sau là mã decompiled từ thư viện:
Mã
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source)
{
return source.DefaultIfEmpty<TSource>(default(TSource));
}
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
return DefaultIfEmptyIterator<TSource>(source, defaultValue);
}
public static TSource First<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
IList<TSource> list = source as IList<TSource>;
if (list != null)
{
if (list.Count > 0)
{
return list[0];
}
}
else
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
return enumerator.Current;
}
}
}
throw Error.NoElements();
}
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
IList<TSource> list = source as IList<TSource>;
if (list != null)
{
if (list.Count > 0)
{
return list[0];
}
}
else
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
return enumerator.Current;
}
}
}
return default(TSource);
}
Và đây là cái gì đó để đề cập đến:
DefaultIfEmpty
có một tình trạng quá tải parameterless, mà gọi sự quá tải tham số với default(TSource)
và trả về kết quả của nó.
Sự khác biệt duy nhất giữa parameterless FirstOrDefault
và First
, là tùy chọn thứ hai sẽ ném khi bộ sưu tập trống.
Để biết thêm thông tin, hãy xem Enumerable.FirstOrDefault<TSource> Method trên MSDN.
FirstOrDefault
ngữ nghĩa biểu thị first or default
và được gọi là; nó không có tên là first or null
. Trong C#, default(T)
cho loại tham chiếu là null, nhưng đối với loại không tham chiếu, không phải loại tham chiếu. Ví dụ: default(int)
bằng không.
Từ khóa default
chưa bao giờ được nói null ngữ nghĩa. Đó là DEFAULT.
Ngoài ra, để biết thêm thông tin, default Keyword trên MSDN.
Nguồn
2013-04-03 08:39:21
Cá nhân tôi thì không. 'DefaultIfEmpty' quan tâm đến số đếm, không phải giá trị vô hướng. Tạo phương thức mở rộng của riêng bạn, có thể được đặt tên cũng là 'FirstOrDefault' lấy đối số' T' để chỉ định làm mặc định. –