Dee Raghav
Dee Raghav

Reputation: 39

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????

Upvotes: 3

Views: 3775

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502835

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.

Upvotes: 6

gzaxx
gzaxx

Reputation: 17600

Use LINQ:

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

Upvotes: 2

Ilya Ivanov
Ilya Ivanov

Reputation: 23646

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

Upvotes: 5

Related Questions