2021年1月23日星期六

Processing an array of "generic tuples" in C#

I have the following problem - I have instances of the following type:

List<int>, int[], List<float>, float[], List<Vector3>, Vector3[]  

etc. The type can vary (though the total amount of possible types is ~7), and for each List<T> I have a specific T[] object. So the objects come in pairs.

At the start I have the List<T>s in a large list, and the T[]s in a large list, but I can put these in whatever structure I want, and I know them a head of time. What I would like is the possibility to call some sort of function, that will for example on a pair

List<int> intList, int[] intArray  

do:

intList.Add(intArray[i])  

for some specific i, but this will be done on all the pairs (we can assume that the i is not out of bounds for any of the arrays).

//

I haven't been able to think of some neat way that would let me do this in a generic way. It's possible to separate the tuples by types, and then process those, but it would very neat if I could do it without that.

EDIT: I've figured out how to get the desired behavior. Some clarification of the problem.

Initially I have two lists A, B that could look something like this:

A = { List<int> a_1, List<float> a_2, List<string> a_3,...}    B = { int[] b_1, float[] b_2, string[] b_3,...}  

And I wanted a method with parameter index that would do

for (int i = 0; i<A.Count; i++)  {      A[i].Add(B[i][index]);  }  

It didn't occur to me that I could make both A, B be of type IList and that things would actually work. I thought that will give an error/won't compile because there is no way to check the type B[i][index] is correct, but I guess dynamic type checking is used in this case.

https://stackoverflow.com/questions/65864138/processing-an-array-of-generic-tuples-in-c-sharp January 24, 2021 at 04:38AM

没有评论:

发表评论