我試圖從我連接它們的庫對象列表中獲取數據深入到我的信息對象中。兩種解決方案我都看起來效率很低。如果linq查詢不是更長的變體,有什麼辦法可以將它減少爲單個OfType調用?在信息對象列表上調用linq最有效的方法是什麼?
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqQueries
{
// Test the linq queries
public class Test
{
public void TestIt()
{
List<ThirdParty> As = new List<ThirdParty>();
// This is nearly the query I want to run, find A and C where B
// and C match criteria
var cData = from a in As
from b in a.myObjects.OfType<MyInfo>()
where b.someProp == 1
from c in b.cs
where c.data == 1
select new {a, c};
// This treats A and B as the same object, which is what I
// really want, but it calls two sub-queries under the hood,
// which seems less efficient
var cDataShorter = from a in As
from c in a.GetCs()
where a.GetMyProp() == 1
where c.data == 1
select new { a, c };
}
}
// library class I can't change
public class ThirdParty
{
// Generic list of objects I can put my info object in
public List<Object> myObjects;
}
// my info class that I add to ThirdParty
public class MyInfo
{
public List<C> cs;
public int someProp;
}
// My extension method for A to simplify some things.
static public class MyExtentionOfThirdPartyClass
{
// Get the first MyInfo in ThirdParty
public static MyInfo GetB(this ThirdParty a)
{
return (from b in a.myObjects.OfType<MyInfo>()
select b).FirstOrDefault();
}
// more hidden linq to slow things down...
public static int GetMyProp(this ThirdParty a)
{
return a.GetB().someProp;
}
// get the list of cs with hidden linq
public static List<C> GetCs(this ThirdParty a)
{
return a.GetB().cs;
}
}
// fairly generic object with data in it
public class C
{
public int data;
}
}
運行這兩個查詢並用秒錶計時。請注意延遲執行。 – 2013-03-07 21:41:48
LINQ針對可讀性和易開發性進行了優化 - 而不是執行速度。如果存在性能問題,請嘗試用一些循環替換LINQ。做一些時間來驗證速度,並在循環上面寫一條評論來解釋它在做什麼。 – 2013-03-07 21:49:12
@DasKrümelmonster鑑於在這裏執行的操作是什麼,我的猜測是LINQ應用的開銷將會小到可以忽略,因爲真正的「工作」不是微不足道的。當真正的「工作」要做的非常快,並且有很多項目時,LINQ開銷會開始被注意到。你需要確定個人資料,但賠率不夠重要。 – Servy 2013-03-07 21:50:43