我有以下代碼(從我的生產代碼中提取),它應該編譯但不能:
public class TestClass
{
public abstract class LocalizableEntity<TLocalizedEntity> where TLocalizedEntity : class, ILocalizedData, new()
{
public abstract string Id { get; set; } // Primary key
public abstract List<TLocalizedEntity> LocalizedData { get; set; }
}
public interface ILocalizedData
{
string CultureName { get; set; }
}
public void MergeData<TEntity, TLocalizedEntity>(IEnumerable<TEntity> newItems)
where TEntity : LocalizableEntity<TLocalizedEntity>
where TLocalizedEntity : class, ILocalizedData, new()
{
// Get the existing items
var existingItems = new List<TEntity>();
// Get the deleted items
var deletedItems = existingItems
.ExceptBy(newItems, x => x.Id, StringComparer.InvariantCultureIgnoreCase);
}
}
問題是 LinqExceptBy函式在通用輸入型別上阻塞。如所寫,該行給了我一個編譯器錯誤,突出顯示ExceptBy并說它無法從用法中推斷出泛型型別引數。
'Enumerable.ExceptBy<TSource, TKey>(IEnumerable<TSource>, IEnumerable<TKey>, Func<TSource, TKey>, IEqualityComparer<TKey>?)'無法從用法中推斷出方法的型別引數。嘗試明確指定型別引數。
如果我修改有問題的陳述句以指定通用型別,我會得到一個不同的錯誤:
var deletedItems = existingItems
.ExceptBy<TEntity, string>(newItems, x => x.Id, StringComparer.InvariantCultureIgnoreCase);
現在編譯器突出顯示existingItems變數并抱怨:
“List”不包含“ExceptBy”的定義,最好的擴展方法多載
'Queryable.ExceptBy<TEntity, string>(IQueryable<TEntity>, IEnumerable<string>, Expression<Func<TEntity, string>>, IEqualityComparer<string>?)'需要“IQueryable”型別的接收器
好的,我不知道這個錯誤訊息中的“接收者”是什么,但它似乎在抱怨existingItemsnot implement IQueryable,所以我這樣添加.AsQueryable:
var deletedItems = existingItems
.AsQueryable()
.ExceptBy<TEntity, string>(newItems, x => x.Id, StringComparer.InvariantCultureIgnoreCase);
現在它認為這newItems是一個IEnumerable<string>(不是一個IEnumerable<TEntity>)并且它抱怨它不能從轉換IEnumerable<TEntity>為IEnumerable<string>
我放棄。我做錯了什么,還是編譯器只是被復雜的泛型型別弄糊涂了?
uj5u.com熱心網友回復:
ExceptBy期望第二個引數(this源可列舉之后的第一個)是鍵串列,而不是源物件的串列。
所以你需要以下
var deletedItems = existingItems
.ExceptBy(newItems.Select(x => x.Id), x => x.Id, StringComparer.InvariantCultureIgnoreCase)
dotnetfiddle
您可以撰寫一個擴展函式來做同樣的事情
public static IEnumerable<TSource> ExceptByKey<TSource, TKey> (
this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey>? comparer = null)
=> first.ExceptBy(second.Select(keySelector), keySelector, comparer);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/484568.html
上一篇:創建公司新聞故事和匹配日期的串列
