copying one Array value to another array

I have 2 array of object. 1st array of object have property which I want to copy to other array.

1st array of object

HotelRoomResponse[] hr=new HotelRoomResponse[100];

2nd array of object

RateInfos[] rt = new RateInfos[100];

now what i want to do is copy a property of 1st array like

rt=hr[].RateInfo;

but it give error. What is correct way to do this????

Jon Skeet
people
quotationmark

You can't just project an array like that. You effectively have to loop - although you don't need to do that manually in your own code. LINQ makes it very easy, for example:

RateInfos[] rt = hr.Select(x => x.RateInfo).ToArray();

Or you could use Array.ConvertAll:

RateInfos[] rt = Array.ConvertAll(hr, x => x.RateInfo);

In both of these cases there's still a loop somewhere - it's just not in your code.

If you're quite new to C# and don't understand LINQ, lambda expressions, delegates etc yet, then you could just write the code yourself:

RateInfos[] rt = new RateInfos[hr.Length];
for (int i = 0; i < rt.Length; i++)
{
    rt[i] = hr[i].RateInfo;
}

All of these three will achieve the same result.

  • The first approach is probably the most idiomatic in modern C#. It will work with any input type, and you can change from ToArray() to ToList() to get a List<RateInfos> instead of an array, etc.
  • The second approach is slightly more efficient than the first and will work with .NET 2.0 (whereas LINQ was introduced in .NET 3.5) - you'll still need a C# 3 compiler or higher though. It will only work as written with arrays, but there's a similar ConvertAll method for List<T>.
  • The third approach is the most efficient, but obviously more code as well. It's simpler for a newcomer to understand, but doesn't express what you're trying to achieve as clearly when you know how all the language features work for the first two solutions.

people

See more on this question at Stackoverflow