有效地選擇一個隨機行,用linq中的濾波器到sql
>>本文探討了從LINQ到SQL查詢的單個隨機行的有效技術,該行包括包含過濾器條件。 我們將重點介紹旨在最大程度地減少數據庫往返和優化性能的方法。
>方法1:模擬用戶定義的功能(UDF)>
此方法利用數據上下文中的自定義函數來生成隨機的GUID,有效地將行順序隨機。>
<code class="language-csharp">partial class MyDataContext { [Function(Name = "NEWID", IsComposable = true)] public Guid Random() { throw new NotImplementedException(); } }</code>>與隨機排序查詢:
<code class="language-csharp">var cust = (from row in ctx.Customers where row.IsActive // Your filter condition orderby ctx.Random() select row).FirstOrDefault();</code>
> 此方法首先檢索過濾行的計數,然後使用此計數生成一個隨機索引進行選擇。
>>過濾查詢:
創建應用您的過濾器的查詢:<code class="language-csharp">var qry = from row in ctx.Customers where row.IsActive select row;</code>
<code class="language-csharp">int count = qry.Count(); // First database round trip</code>
<code class="language-csharp">int index = new Random().Next(count);</code>和
Skip
性能考慮:FirstOrDefault
<code class="language-csharp">Customer cust = qry.Skip(index).FirstOrDefault(); // Second database round trip</code>
以上是如何在 LINQ to SQL 中使用篩選器有效率地擷取隨機行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!