Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

In C# how can I create an array of arrays based on an array of objects?

I have an array of 4 objects. These objects are all of the same type and have many fields. I want to extract the fields Name, Code and Date from each object, put those values in a new array (one new array for each object) and then place these new arrays in an array. So I'd end up with an array like


Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Quite easy with LINQ:

//Assuming you have a variable "list" with your objects
var list = ........

var newList = list.Select(x => new[] { x.Name, x.Code, x.Date }).ToArray();

(shamefully not tested, pure notepad developing)

The first Select creates a new array for each object, containing the 3 elements from the 3 properties. The final ToArray call creates a new array containing the result of the Select, that is, each object turned into an array.

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share