This question already has answers here:
c# list<int> how to insert a new value in between two values
(5 answers)
Closed 5 years ago.
Im seeking for a tiny help with a List I have
So, I have a List, which can change at any time, its quite long so I wont post it,
I want to get a specific position because I want to insert a new Line into it outside of its source. Here is a small thing that might explain it
Before
public class ListSourceView
{
public List<Stuff> Blah = new List<Stuff>("Hello", "Principal", "Johnson,", "How are you?");
}
So, we have a List called Blah with 4 things in it, now I would like to put a new String before Principal, but regardless if there are more strings in the list. (Aka Blah.Insert(2, "Mr") would not work) Best Case scenario would be something like Blah.Insert(Principal.positionInTheList - 1, "Mr") but am unsure what to use here.
Hope ya help a buddy out
You can use:
int index = Blah.FindIndex(a => a.StartsWith("Principal"));
then you can insert a new item at/before/after the index by using
Blah.Insert(index, "newEntry"); //at index
Blah.Insert(index - 1, "newEntry"); //before index
Blah.Insert(index + 1, "newEntry"); //after index
Related
This question already has answers here:
Variables in a loop
(9 answers)
Loop through object variables with different number on the name [duplicate]
(5 answers)
Iteration with variable name [duplicate]
(1 answer)
Closed 2 years ago.
I am trying to use a for loop to iterate through a series of variable names each ending in a number from 1 to 10. I have seen a few other answers to this question but have been unable to make any work for my specific situation. My code is as follows:
string cat2Pos0 = cat2[0];
int numOfPos0 = cat2.Where(x => x.Equals(cat2Pos0)).Count();
List<int> indexOfPos0 = new List<int>();
bool check = cat2.Contains(cat2Pos0);
int index = 0;
if (check == true)
{
for (int i = 0; i < numOfPos0; i++)
{
index = cat2.FindIndex(x => x == cat2Pos0);
indexOfPos0.Add(cat2.IndexOf(cat2Pos0));
}
}
else if (cat2Pos0 == "-")
{
numOfPos0 = 17;
}
I need to loop through 10 variables names cat1 - cat10. In the code: whenever there is the phrase "cat" I need to be able to adjust it depending on a for loop e.g. cat1 or cat5:
string cat3pos0 = cat3[0];
or:
index = cat3.FindIndex(x => x == cat3Pos0);
Unfortuantely, I am unable to simply write out each variation individually as that would use up almost 3700 lines of code and I was hoping that there would be a better way of achieveing this.
Many thanks, all help is greatly appreciated,
Josh
See here how to use reflection for this. (something like this.GetType().GetField("cat" + i.ToString());.)
But I would really suggest changing your variables to one array of 10 variables. So cat will be an array of arrays (since your cat's seem to be arrays).
This question already has answers here:
How can I sort a List<T> by multiple T.attributes?
(3 answers)
Closed 4 years ago.
I was wondering if it is possible to combine my sorting code into one ?
I sort my array firstly by enum, then by an id number from lowest to highest.
So my current code looks like this:
_entities = _entities.OrderBy(a => a.Priority).ToArray(); //sort by enum
_entities = _entities.OrderBy(a => a.PriorityID).ToArray(); //then sort by id
So the enum has:
High, Medium,Low
And IDs are just integers.
So the end result should be like:
High¬
0 , 1 ,2
Medium¬
0, 1, 2
Low¬
0, 1, 2
I don't know the syntax to combine these, or if this is as simple as it gets? But it does seem a bit inefficient to be sorting by each property one by one.
Whats the correct way to do ths?
You can use ThenBy:
_entities = _entities.OrderBy(a => a.Priority).ThenBy(a => a.PriorityID).ToArray();
This question already has answers here:
How to get first N elements of a list in C#?
(7 answers)
How do I clone a range of array elements to a new array?
(26 answers)
Closed 5 years ago.
I'm training C# on a simple card game. I have methods that shuffle and deals the cards. I have a random deck that is well generated.
Is it possible to set an array for the player1 cards, picking up the first ten values of the array.
Here is a part of my code :
currentCard = 0;
public Card DealCard()
{
if (currentCard < deck.Length)
return deck[currentCard++];
else
return null;
}
I want to pick up for example ten first values of
deck[currentCard++]
Any suggestions will be appreciated, thanks for your help !
You mean you want to pull the first 10 enties into another array? Something like;
var player1Cards = deck.Take(10);
or
List<int> player1Cards = new List<int>();
for (int i = 0; i < 10; i++){
player1Cards.Add(deck[i]);
}
This question already has answers here:
Natural Sort Order in C#
(18 answers)
Closed 6 years ago.
I am trying to sort an ArrayList filled with strings alphabetically. When I call the Sort method the alphabet seems to sort fine, however when there are numbers involved the Sort method seems to sort incorrectly.
Take this code for example:
ArrayList list = new ArrayList ();
list.Add ("img149");
list.Add ("img15");
list.Add ("a");
list.Sort ();
for (int i = 0; i < list.Count (); i++) {
Console.WriteLine (list [i]);
}
This seems to print:
a
img_149
img_15
the string "a" is sorted fine, but the two other strings are incorrectly sorted. I think I understand why this is as "4" comes before "5" however, 149 is really higher than 15 in which case the string with the 15 should print first.
For my situation, I never know exactly what the strings will be (the strings represent file names in my program), and it is crucial the names are sorted alphabetically with the numbers in order (1, 2, 150, 300, etc.). Does anyone have any ideas on how to rectify this?
It is sorting correctly. Try this:
List<string> sortedFileNames = list.Cast<string>().OrderBy(s =>
{
string numericStr = Regex.Match(s, #"\d+").Value;
if (numericStr == "")
{
return s; // file name does not include number, so just sort by actual file name.
}
else
{
return s + numeric.PadLeft(10, '0'); // file name includes numbers, so sort by file name with number zero-padded to fixed length of 10.
}
}).ToList();
I have a problem very much like the one mentioned here:
ArgumentOutOfRangeException Was Unhandled
I believe that contiguousLines[columnNum].Add(...) is what is causing the error because I am indexing with columnNum
List<line> freeLines = new List<line>();
List<List<line>> contiguousLines = new List<List<line>>();
while(freeLines.Count > 0)
{
int columnNum = contiguousLines.Count;
contiguousLines[columnNum].Add(freeLines[0]);
freeLines.RemoveAt(0);
for(int i = 0; i < freeLines.Count; i++)
{
int last = contiguousLines[columnNum].Count;
if(contiguousLines[columnNum][last].upDown(freeLines[i]))
{
contiguousLines[columnNum].Add(freeLines[i]);
freeLines.RemoveAt(i);
i = -1;
}
}
// Further code that pulls individual elements from freeLines and
// is intended to place them into contiguousLines.
}
The function upDown just compares Start and End points of the lines to see if one (freeLines[i]) is the downstream of the other (contiguousLines[columnNum]).
System.ArgumentOutOfRangeException was unhandled
Message=Index was out of range. Must be non-negative and less than the size of
the collection. Parameter name: index
What is the proper syntax when dealing with a List of Lists?
(Note: I don't often program in C# and this project is something I wrote and have working in C++ only to be later informed C# would play better with the rest of the utilities for my job. In C++ I used vectors for my containers, but apparently copy/pasting the logic won't work as there is some nuance of Lists that I am unaware of.)
I suppose it is also possible to just make a ContiguousLine class that holds a list of Lines, then add to a List<ContiguousLine> from freeLines. Even if that were to be a better solution, I am still curious why I can not address a List of Lists of Lines in this way.
int last = contiguousLines[columnNum].Count;
As lists are 0-indexed, you're 1 over.
you need to add a List first before access the column
contiguousLines.Add(new List<line>());
contiguousLines[columnNum].Add(freeLines[0]);