Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在本例中,LINQtoArray能否返回强类型数组?_Linq_Linq To Objects - Fatal编程技术网

在本例中,LINQtoArray能否返回强类型数组?

在本例中,LINQtoArray能否返回强类型数组?,linq,linq-to-objects,Linq,Linq To Objects,我设计了这个例子,因为它是我试图解决的实际问题的一个容易理解的版本。下面是类及其关系 首先,我们有一个Country类,它包含一个由字符串(例如名称或缩写)索引的状态对象字典。State类的内容与此无关: class Country { Dictionary<string, State> states; } class State { ... } 我想要的是一个包含分支的状态对象数组。下面是我写的LINQ。首先,它获取所有实际包含分支机构的公司,然后通过比较两个列表的键加

我设计了这个例子,因为它是我试图解决的实际问题的一个容易理解的版本。下面是类及其关系

首先,我们有一个Country类,它包含一个由字符串(例如名称或缩写)索引的状态对象字典。State类的内容与此无关:

class Country
{
    Dictionary<string, State> states;
}

class State { ... }
我想要的是一个包含分支的状态对象数组。下面是我写的LINQ。首先,它获取所有实际包含分支机构的公司,然后通过比较两个列表的键加入到州列表中

问题是
ToArray
返回匿名类型。我理解为什么匿名类型不能转换为强类型。我试图弄清楚是否可以更改某些内容以返回强类型数组。(我愿意接受关于编写LINQ的更好方法的建议。)

我已经试着在所有的地方(在前面,在列表2,在最后的选择,和其他不太可能的候选人)选分公司

你可以做:

 select new MyClassOfSomeType {
   ..
)
对于选择,可以为其指定自定义类类型。然后还可以使用ToList。使用ArrayList,如果需要将其保持为松散类型,则可以在以后使用Cast将其设置为强类型,尽管只适用于不生成匿名类的任何选择结果


HTH.

如果我理解正确,您只需要在其中有office分支机构的州,而不是分支机构。如果是,一个可能的linq如下所示:

State[] offices =
(from cm in companies
 where cm.branches.Count > 0
 from br in cm.branches
 join st in usa.states on br.Key equals st.Key
 select st.Value
).Distinct().ToArray();
如果同时需要状态和分支,则必须执行group by,结果将是IEnumerable>,之后可以进行处理

var statesAndBranches =
from cm in companies
where cm.branches.Count > 0
from br in cm.branches
join st in usa.states on br.Key equals st.Key
group br.Value by st.Value into g
select g;

还有一件事,即使您将国家/地区和分支机构声明为字典,它们也被用作IEnumerable(来自字典中的keyValuePair),因此您不会从中获得任何性能好处

您的
分支机构
类是什么样子的?
 select new MyClassOfSomeType {
   ..
)
State[] offices =
(from cm in companies
 where cm.branches.Count > 0
 from br in cm.branches
 join st in usa.states on br.Key equals st.Key
 select st.Value
).Distinct().ToArray();
var statesAndBranches =
from cm in companies
where cm.branches.Count > 0
from br in cm.branches
join st in usa.states on br.Key equals st.Key
group br.Value by st.Value into g
select g;