我有一个第三方库返回一个对象数组的对象数组,我可以把它放入一个对象[]:
object[] arr = myLib.GetData(...);
结果数组由object []条目组成,因此您可以将返回值视为某种记录集,其中外部数组表示行,而内部数组包含可能未填充某些字段的字段值(锯齿状数组) 。要访问各个字段,我必须像:
int i = (int) ((object[])arr[row])[col];//access a field containing an int
现在,因为我很懒,我想访问这样的元素:
int i = (int) arr[row][col];
为此,我使用以下Linq查询:
object[] result = myLib.GetData(...);
object[][] arr = result.Select(o => (object[])o ).ToArray();
我尝试使用简单的演员 object[][] arr = (object[][])result;
但是因运行时错误而失败。
现在,我的问题:
- 有更简单的方法吗?我有一些感觉 漂亮的演员应该做的伎俩?
- 我也担心表现 因为我必须重塑大量数据只是为了节省一些铸件,所以我 想知道这真的值得吗?
编辑:
谢谢大家的快速回答。
@James:我喜欢你在新课程中结束罪魁祸首的答案,但缺点是我在接收源数组时总是必须进行Linq包装,而索引器需要row和col值 int i = (int) arr[row, col];
(我需要得到一个完整的行 object[] row = arr[row];
,抱歉没有在开头发帖)。
@Sergiu Mindras:像詹姆斯一样,我觉得扩展方法有点危险,因为它适用于所有人 object[]
变量。
@Nair:我为我的实现选择了你的答案,因为它不需要使用Linq包装器,我可以使用它来访问两个单独的字段 int i = (int) arr[row][col];
或使用整行 object[] row = arr[row];
@quetzalcoatl和@Abe Heidebrecht:谢谢你的提示 Cast<>()
。
结论: 我希望我可以选择James'和Nair的答案,但正如我上面所说,Nair的解决方案让我(我认为)具有最佳的灵活性和性能。 我添加了一个函数,它将使用上面的Linq语句“展平”内部数组,因为我还有其他需要使用这种结构的函数。
以下是我(大致)实现它的方式(取自Nair的解决方案:
公共类CustomArray { 私有对象[]数据; public CustomArray(object [] arr) { data = arr; }
//get a row of the data
public object[] this[int index]
{ get { return (object[]) data[index]; } }
//get a field from the data
public object this[int row, int col]
{ get { return ((object[])data[row])[col]; } }
//get the array as 'real' 2D - Array
public object[][] Data2D()
{//this could be cached in case it is accessed more than once
return data.Select(o => (object[])o ).ToArray()
}
static void Main()
{
var ca = new CustomArray(new object[] {
new object[] {1,2,3,4,5 },
new object[] {1,2,3,4 },
new object[] {1,2 } });
var row = ca[1]; //gets a full row
int i = (int) ca[2,1]; //gets a field
int j = (int) ca[2][1]; //gets me the same field
object[][] arr = ca.Data2D(); //gets the complete array as 2D-array
}
}
所以 - 再次 - 谢谢大家!使用这个网站总是一种真正的乐趣和启示。