I have to access Dictionary<TKey, TValue> value by key (that I get from array I'm creating inline) like so:
var someString = "1.2.3";
someDictionary[someString.Split('.').ToArray()[ /---> self.Length <---/ - 1 ]];
Question: Is it possible to get array Length inline without creating new variable and assigning array to it?
You cannot do this. You need to store intermediate value in a variable if you want to access it twice.
I see no sense in trying to do this without additional variable - at least, your approach is absolutely unreadable.
However, as I understand, by [self.Length - 1] you want to access the last value in this array.
If yes, then you can just use LINQ .Last:
var someString = "1.2.3";
someDictionary[someString.Split('.').Last()]; // someDictionary["3"]
Related
I have used Splits in the past, but this one is a bit different for some reason, and I am not sure why...
Code:
string responceuptime = scripting.ReadUntilPrompt();
string[] suptime = responceuptime.Split('s');
UpTime.Text = suptime;
Error:
cannot implicitly convert type string[] to string
That is very basic thing and is very easy to figure out from the error message what is wrong actually.
The following line is the culprit by the way here:
UpTime.Text = suptime;
As suptime is of type string[] which is array while Text property is of type String. When assigning references to and from the type should be same otherwise we will see this error message which you just facing.
It's unclear from the above lines of code that what you are trying to achieve here, but you would need to assign single String object to Text, you cannot assign array or collection to single String object.
Hope it helps.
Your variable suptime is a string[] - an array of strings. While I don't know what Uptime.Text is, I'm guessing that it's looking for a single string, and that's why you're getting the compiler error that you are.
If you want to get the first string out of the array, then you could set it like so:
UpTime.Text = suptime[0];
The output of a call to String.Split is an array of strings (String[]). What your code does, here, is attempting to assign a String[] to a String variable, therefore the application is throwing an exception.
Hence, you must identify, within your array, the value you are looking for and picking the index that points to it (from 0 to suptime.Length - 1). For example:
UpTime.Text = suptime[0]; // first value of the array
UpTime.Text = suptime[2]; // third value of the array
UpTime.Text = suptime[suptime.Length - 1]; // last value of the array
If the result of your split is:
{"A" "Z" "11:57"}
and you want your UpTime.Text to be filled with something that looks like a time value, it's kinda obvious that the value you must pick is the third one.
In C, if we have an array, we can pass it by reference to a function. We can also use simple addition of (n-1) to pass the reference starting from n-th element of the array like this:
char *strArr[5];
char *str1 = "I want that!\n";
char *str2 = "I want this!\n";
char *str3 = "I want those!\n";
char *str4 = "I want these!\n";
char *str5 = "I want them!\n";
strArr[0] = str1;
strArr[1] = str2;
strArr[2] = str3;
strArr[3] = str4;
strArr[4] = str5;
printPartially(strArr + 1, 4); //we can pass like this to start printing from 2nd element
....
void printPartially(char** strArrPart, char size){
int i;
for (i = 0; i < size; ++i)
printf(strArrPart[i]);
}
Resulting in these:
I want this!
I want those!
I want these!
I want them!
Process returned 0 (0x0) execution time : 0.006 s
Press any key to continue.
In C#, we can also pass reference to an object by ref (or, out). The object includes array, which is the whole array (or at least, this is how I suppose it works). But how are we to pass by reference to the n-th element of the array such that internal to the function, there is only string[] whose elements are one less than the original string[] without the need to create new array?
Must we use unsafe? I am looking for a solution (if possible) without unsafe
Edit:
I understand that we could pass Array in C# without ref keyword. Perhaps my question sounds quite misleading by mentioning ref when we talk about Array. The point why I put ref there, I should rather put it this way: is the ref keyword can be used, say, to pass the reference to n-th element of the array as much as C does other than passing reference to any object (without mentioning the n-th element or something alike)? My apology for any misunderstanding occurs by my question's phrasing.
The "safe" approach would be to pass an ArraySegment struct instead.
You can of course pass a pointer to a character using unsafe c#, but then you need to worry about buffer overruns.
Incidentally, an Array in C# is (usually) allocated on the heap, so passing it normally (without ref) doesn't mean copying the array- it's still a reference that is passed (just a new one).
Edit:
You won't be able to do it as you do in C in safe code.
A C# array (i.e. string[]) is derived from abstract type Array.
It is not only a simple memory block as it is in C.
So you can't send one of it's element's reference and start iterate from there.
But there are some solutions which will give you the same taste of course (without unsafe):
Like:
As #Chris mentioned you can use ArraySegment<T>.
As Array is also an IEnumerable<T> you can use .Skip and send the returned value. (but this will give you an IEnumerable<T> instead of an Array). But it will allow you iterate.
etc...
If the method should only read from the array, you can use linq:
string[] strings = {"str1", "str2", "str3", ...."str10"};
print(strings.Skip(1).Take(4).ToArray());
Your confusion is a very common one. The essential point is realizing that "reference types" and "passing by reference" (ref keyboard) are totally independent. In this specific case, since string[] is a reference type (as are all arrays), it means the object is not copied when you pass it around, hence you are always referring to the same object.
Modified Version of C# Code:
string[] strArr = new string[5];
strArr[0] = "I want that!\n";
strArr[1] = "I want this!\n";
strArr[2] = "I want those!\n";
strArr[3] = "I want these!\n";
strArr[4] = "I want them!\n";
printPartially(strArr.Skip(1).Take(4).ToArray());
void printPartially(string[] strArr)
{
foreach (string str in strArr)
{
Console.WriteLine(str);
}
}
Question is old, but maybe answer will be useful for someone.
As of C# 7.2 there are much more types to use in that case, ex. Span or Memory.
They allow exactly for the thing you mentioned in your question (and much more).
Here's great article about them
Currently, if you want to use them, remeber to add <LangVersion>7.2</LangVersion> in .csproj file of your project to use C# 7.2 features
I've recently started using c# moving over from Java. I can't seem to find how to get a list item by index. In java to get the first item of the list it would be:
list1.get(0);
What is the equivalent in c#?
list1[0];
Assuming list's type has an indexer defined.
You can use the ElementAt extension method on the list.
For example:
// Get the first item from the list
using System.Linq;
var myList = new List<string>{ "Yes", "No", "Maybe"};
var firstItem = myList.ElementAt(0);
// Do something with firstItem
Visual Basic, C#, and C++ all have syntax for accessing the Item property without using its name. Instead, the variable containing the List is used as if it were an array:
List[index]
See, for instance, List.Item[Int32] Property.
.NET List data structure is an Array in a "mutable shell".
So you can use indexes for accessing to it's elements like:
var firstElement = myList[0];
var secondElement = myList[1];
Starting with C# 8.0 you can use Index and Range classes for accessing elements. They provides accessing from the end of sequence or just access a specific part of sequence:
var lastElement = myList[^1]; // Using Index
var fiveElements = myList[2..7]; // Using Range, note that 7 is exclusive
You can combine indexes and ranges together:
var elementsFromThirdToEnd = myList[2..^0]; // Index and Range together
Also you can use LINQ ElementAt method but for 99% of cases this is really not necessary and just slow performance solution.
Old question, but I see that this thread was fairly recently active, so I'll go ahead and throw in my two cents:
Pretty much exactly what Mitch said. Assuming proper indexing, you can just go ahead and use square bracket notation as if you were accessing an array. In addition to using the numeric index, though, if your members have specific names, you can often do kind of a simultaneous search/access by typing something like:
var temp = list1["DesiredMember"];
The more you know, right?
you can use index to access list elements
List<string> list1 = new List<string>();
list1[0] //for getting the first element of the list
Let's say that I have 2 string arrays with different values:
string[] sArray1 = new string[3]{"a","b","c"};
string[] sArray2 = new string[3]{"e","f","g"}
And I want to make values of sArray1 equal to values of sArray2 (I know I can write it like this) : sArray1[0] = sArray2[0]; sArray1[1]= sArray2[1]; sArray1[2]=sArray2[2];
For 3 values it's easy, but what if I had 100 values in an array? Is there any other way that I can make array values equal?
p.s. sorry for my bad English :(
Something like this (with a little error checking):
if (sArray2.Length == sArray1.Length)
{
sArray2.CopyTo(sArray1, 0);
}
Regards
I'm assuming you want to keep the reference to the original array in sArray1? Then do this:-
Array.Copy(sArray2, sArray1, sArray1.Length);
If you want them to function independently of each other than you can use .Clone() as of .NET 5.0
string[] sArray1 = (string[])sArray2.Clone();
In the above scenario if you change a value in one array it will not affect the other - this is called a "shallow copy" (AKA copy by val). If you want the values in both arrays to be tied to each other (typically not desirable) you can do a simple assignment like this:
string[] sArray1 = sArray2;
In this case if you change a value in either array the value(s) in the other array will update (AKA copy by ref).
I've just started learning C# and in the introduction to arrays they showed how to establish a variable as an array but is seems that one must specify the length of the array at assignment, so what if I don't know the length of the array?
Arrays must be assigned a length. To allow for any number of elements, use the List class.
For example:
List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3
Use List<> to build up an 'array' of unknown length.
Use List<>.ToArray() to return a real array, and not a List.
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();
A little background information:
As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.
And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.
You can create an array with the size set to a variable, i.e.
int size = 50;
string[] words = new string[size]; // contains 50 strings
However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.
Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.
Search for them in System.Collections and System.Collections.Generics.
You might also want to look into Dictionarys if your data is unique, This will give you two columns to work with.
User name , Total bill
it gives you a lot of built in tools to search and update just the value.
var yummy = new List<string>();
while(person.FeelsHappy()) {
yummy.Add(person.GetNewFavoriteFood());
}
Console.WriteLine("Sweet! I have a list of size {0}.", list.Count);
Console.WriteLine("I didn't even need to know how big to make it " +
"until I finished making it!");
try a generic list instead of array
In a nutshell, please use Collections and Generics.
It's a must for any C# developer, it's worth spending time to learn :)
As detailed above, the generic List<> is the best way of doing it.
If you're stuck in .NET 1.*, then you will have to use the ArrayList class instead. This does not have compile-time type checking and you also have to add casting - messy.
Successive versions have also implemented various variations - including thread safe variants.
If you really need to use an array instead of a list, then you can create an array whose size is calculated at run time like so...
e.g i want a two dimensional array of size n by n. n will be gotten at run time from the user
int n = 0;
bool isInteger = int.TryParse(Console.ReadLine(), out n);
var x = new int[n,n];