亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

你如何知道一個集合將充當 IEnumerable 還是 IQueryable?

你如何知道一個集合將充當 IEnumerable 還是 IQueryable?

C#
郎朗坤 2023-08-13 16:29:48
我有這行代碼:var attachments = EntityRepository<Attachment>().Entities .Where(at => at.EntityType == EntityType.EmailTemplate) .ToDictionary(at => at.Extension, at => at);EntityRepository<Attachment>().EntitiesSystem.Data.Entity.Infrastructure.DbQuery<TResult>是同時實現IQueryable<TResult>和 的類型IEnumerable<TResult>。我如何確定它是否充當IEnumerable<T>(即從數據庫中檢索所有行,然后在 C# 中進行過濾)或充當IQueryable<T>(將 C# 謂詞轉換為 SQL 查詢并僅檢索這些行)。
查看完整描述

2 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

我想你可能對這個有一個小小的誤解IEnumerable。它只是說該類支持迭代。它不會直接影響數據的獲取方式。

此外,IQueryable實現IEnumerable,因此所有IQueryable實例也是IEnumerable。這是有道理的,因為您可以迭代結果。

在您的示例中,缺少這意味著IQueryable“從數據庫檢索所有行,然后在 C# 中進行過濾”。


查看完整回答
反對 回復 2023-08-13
?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

LINQ 中有 2 個不同的擴展 -?IEnumerable和IQueryable。

當您編寫EntityRepository<Attachment>().Entities .Where(at => at.EntityType == EntityType.EmailTemplate)編譯器時,它會檢查類型Entities,并聲明“更具體”,IQueryable編譯器會選擇Queryable.Where()方法,并且表達式由IQueryProvider轉換為 SQL。當您編寫時,.ToDictionary(at => at.Extension, at => at)編譯器找不到Queryable.ToDictionary(),因此它會回退到Enumerable.ToDictionary()內存中過濾項目。

C# 語言規范中定義了擴展方法調用規則:

  • 候選方法集被簡化為僅包含來自最派生類型的C.F方法:對于集合中的每個方法,其中C是聲明該方法的類型F,所有在 的基類型中聲明的方法都C將從集合中刪除。此外,如果C是 以外的類類型object,則接口類型中聲明的所有方法都將從集合中刪除。(后一條規則僅在方法組是對具有除 object 之外的有效基類和非空有效接口集的類型參數進行成員查找的結果時才有效。)

?public interface IInterfaceA { }

? ? public interface IInterfaceB : IInterfaceA { }


? ? public static class MyExtensions {

? ? ? ? public static void Print(this IInterfaceA a) => Console.WriteLine("A");

? ? ? ? public static void Print(this IInterfaceB b) => Console.WriteLine("B");

? ? }


? ? public class AB: IInterfaceA, IInterfaceB { }

? ? public class BA: IInterfaceB, IInterfaceA { }


? ? public partial class Program

? ? {

? ? ? ? static void Main(string[] args)

? ? ? ? {

? ? ? ? ? ? new AB().Print(); // B

? ? ? ? ? ? new BA().Print(); // B

? ? ? ? }

? ? }


查看完整回答
反對 回復 2023-08-13
  • 2 回答
  • 0 關注
  • 150 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號