我试图从我附加的库对象列表中获取我的信息对象中的数据。我拥有的两种解决方案似乎都非常低效。有没有办法将其减少为单个 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;
}
}