Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
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

[
   ["Bob","001","1/19/2021"],
   ["Tom","002","1/17/2021"],
   ["Dave","003","1/14/2021"],
   ["John","004","1/9/2021"]
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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 OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...