copying one Array value to another array - c#

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

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.

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

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

Related

Shorthand of Deedle create new series of fixed length

What is the best practice to create an empty Series of fixed length LEN ?
This is what I use now, a bit verbose with Enumerable Range and .Select()
Deedle.Series<int, double> newFixedSeries = Enumerable.Range(0, LEN).Select(idx => 0d).ToOrdinalSeries();
The method you are using looks completely reasonable to me. If you want to make it nicer, you can always define your own helper method and then use that. Another alternative I can think of is to use the Series constructor, which is a little bit shorter, but not hugely:
// Your original approach
var s = Enumerable.Range(0, LEN).Select(idx => 0d).ToOrdinalSeries();
// Using the Series constructor
var s = new Series<int, float>(new int[10], new float[10]);
That said, the Deedle series is an immutable data type, so I cannot think of many cases where you would actually need to create a series filled with zeros - there is not much you can do with such a series. I expect that the thing you are trying to do with the zero-filled series might be better done in some other way.

ILNumerics equivalent of MatLab/Octave statement

Question
In MatLab/Octave, I have the statement x(isnan(x)) = 0. I am porting this over to ILNumerics in C#. I am having trouble finding the ILNumerics equivalent to the MatLab/Octave statement mentioned.
In our case, x is a 2x2 array.
What we've tried
noNaNDataValues = dataValues[ILMath.isnan(dataValues)] = 0.0; where dataValues is an ILArray<double>
We have resorted to standard C# for loops and that works fine. But we would rather use ILNumerics considering how much we've invested in it already.
Just use
x[isnan(x)] = 0;
This is directly equivalent to Matlabs syntax. Your first attempt suggests that you want to seperate non-NaN values from NaNs? If so, please clarify.

Convert loop to LINQ

A list of Equity Analytics (stocks) objects doing a calculation for daily returns.
Was thinking there must be a pairwise solution to do this:
for(int i = 0; i < sdata.Count; i++){
sdata[i].DailyReturn = (i > 0) ? (sdata[i-1].AdjClose/sdata[i].AdjClose) - 1
: 0.0;
}
LINQ stands for: "Language-Integrated Query".
LINQ should not be used and almost can't be used for assignments, LINQ doesn't change the given IEnumerable parameter but creates a new one.
As suggest in a comment below, there is a way to create a new IEnumerable with LINQ, it will be slower, and a lot less readable.
Though LINQ is nice, an important thing is to know when not to use it.
Just use the good old for loop.
I'm new to LINQ, I started using it because of stackoverflow so I tried to play with your question, and I know this may attract downvotes but I tried and it does what you want in case there is at least one element in the list.
sdata[0].DailyReturn = 0.0;
sdata.GetRange(1, sdata.Count - 1).ForEach(c => c.DailyReturn = (sdata[sdata.IndexOf(c)-1].AdjClose / c.AdjClose) - 1);
But must say that avoiding for loops isn't the best practice. from my point of view, LINQ should be used where convenient and not everywhere. Good old loops are sometimes easier to maintain.

How to sort a list by the 2nd tuple element in python and C#

I had a list of tuples where every tuple consists of two integers and I wanted to sort by the 2nd integer. After looking in the python help I got this:
sorted(myList, key=lambda x: x[1])
which is great. My question is, is there an equally succinct way of doing this in C# (the language I have to work in)? I know the obvious answer involving creating classes and specifying an anonymous delegate for the whole compare step but perhaps there is a linq oriented way as well. Thanks in advance for any suggestions.
Another way to do it in python is this
from operator import itemgetter
sorted(myList, key=itemgetter(1))
Assuming that the list of tuples has a type IEnumerable<Tuple<int, int>> (a sequence of tuples represented using Tuple<..> class from .NET 4.0), you can write the following using LINQ extension methods:
var result = myList.OrderBy(k => k.Item2);
In the code k.Item2 returns the second component of the tuple - in C#, this is a property (because accessing item by index wouldn't be type-safe in general). Otherwise, I think that the code is pretty succinct (also thanks to nice lambda function notation).
Using the LINQ query syntax, you could write it like this (although the first version is IMHO more readable and definitely more succinct):
var result = from k in myList orderby k.Item2 select k;

How to check Array of strings contains a particular string?

I'm using .NET 2.0
I have a large array of string.
I want to check whether a particular string is there in the array or not,
I'm not sure, whether following code is optimized or I need to make it more optimized.
please guide.
string []test_arr= new string[]{"key1","key2","key3"};
Boolean testCondition = (new List<string>(test_arr)).Contains("key3");
I also wants to know more about
.NET Generics
.NET Attributes
.NET Reflections
is there any good reference or book, that someone has already refer then help me out !
string []test_arr= new string[]{"key1","key2","key3"};
bool testCondition = Array.Exists
(
test_arr,
delegate(string s) { return s == "key3";}
);
If its possible you could sort your array (using static Array.Sort method) and then use Array.BinarySearch
Alternatively you need to use a more optimised data structure for your strings.
My answer very similar to Matt Howells.
But I'm suggesting to use StringComparison
Array.Exists<string>(stringsArray,
delegate(string match)
{
return match.Equals("key", StringComparison.InvariantCultureIgnoreCase)
});
In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable generic interfaces.
Hence you can do the following:
string[] test_arr = new string[]{"key1","key2","key3"};
Boolean testCondition = ((IList<string>)test_arr).Contains("key3");
List is O(n), SortedList is O(log n)
abouot your larga array of string:
there is no optimized way as long as you use an array (you have to start at the first element and go through each until you find it - or go through the whole array if you dont) - this gives you a worst case time of O(n) (O notation gives the time a program needs to accomplish something).
Since you want to optimize for search I suggest you use a hashtable or tree instead (depending on how large your dataset is). This will greatly reduce the time you need to check
In your sample the biggest overhead will probably be the creation of the List, but that may be part of the demonstration.
Starting from array, the following will probably be faster:
int x = Array.IndexOf<string>(test_arr, "key3");
bool testCondition = x >= 0;
But if you have the option, it would be more efficient to use a HashSet<string> to store them in the first place. HashSet can check the existence of an element in O(1).
Regarding your other questions, they have already been asked on SO, use the search option, for instance with "C# books"

Categories