I am creating an array of string[] in my c# program to save location ("name","Position") of a bunch of elements. The problem is any time I had to introduce a new element I have to change the code at several places according to index of elements:
string[] list = new string[4];
list[0] = "[ELEMENT #1 NAME],[ELEMENT #1POSITION]";
list[1] = "[ELEMENT #2 NAME],[ELEMENT #2POSITION]";
list[2] = "[ELEMENT #3 NAME],[ELEMENT #3POSITION]";
list[3] = "[ELEMENT #4 NAME],[ELEMENT #4POSITION]";
What I am looking for is something like an dynamic array so that I do not have to change the index location every time I introduce/ remove an element from list.
You can use List<string> as a dynamic array, it supports IEnumerable<string> for enumerating, or you can call LINQ and ToArray().
For example:
var list = new List<string>();
list.Add("[ELEMENT #1 NAME],[ELEMENT #1POSITION]");
string array[] = list.ToArray();
However, I'd actually recommend a dictionary in this case and not a list, a dictionary will let you store key-value pairs.
For example:
var dict = new Dictionary<string,int>();
dict["Element #1 Name"] = #Element #1 Position#;
Note that I've no real idea what type the position is, could be an int, a string or even a Point, but you get the idea.
You then don't need to bother with indices but refer to everything by name:
var el1_pos = dict["Element #1 Name"];
var el999_pos = dict["Element #999 Name"];
You can use List<T> if you want a dynamically sized collection and don't bother with the index. And you should also create a type with two properties (Name and Position) and have a list of that type instead of storing them as string. It's easier to maintain, you don't have to parse the string every time you wanna get/set the Name or Position of a particular object.
Normally, you would just use a List<String> here. The Add method allows you to just add an element, no indexing required.
List<string> list = new List<string>();
list.Add("Test");
In your case, since you have "Name" and "Position" associated with each other, consider using a List<PositionedThing> (a custom class in other words) or a Dictionary<String, String> to store your mappings.
The class would look like:
public class PositionedThing
{
public String Name {get; set;}
public String Position {get; set;}
}
Try
List<string> list = new List<string>();
list.Add("[ELEMENT #1 NAME],[ELEMENT #1POSITION]")
Unless I've misunderstood your question that should be what you want
Related
public class LIST
{
public double num;
public double longi;
public double ux;
public double vy;
}
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
L1.ux= // I take l1.ux from stream reader by reading a file and made this
for
L1.vy=.. the other parameters
L1.longi=..
L1.num=....
LIST1.Add(L1)
Here my problem is ı made a list that contains 4 parameters. But ı want to find just one parameter value for instance L1.num how can I take this value from a list?
var indexOfLISTObject = 1 //you need to know which object from LIST1 you want to use
var numParamOfLISTObject = LIST1[indexOfLISTObject].num;
Please Don't name your object LIST. It will create readability issues down the line for you. Name the object what a particular item in your list will represent.
To access a particular property from an item in list you can do following
List l1 = new list();
//Add items ...
//Print property from particular index
Console.WriteLine(l1[index].propertyname);
Put the paremeters inside a list one by one.
in your example you want the parameter num.
List parameterNum = new List();
parameterNum = l1.Select(x => x.Num).ToList();
parameterNum has now the list of Num from l1 list.
If you mean to find/search for a particular value, you could also use System.Linq. For example if you would like to find a member where num is set to 2, you could do this:
LIST1.Where(item=>item.num==2).FirstOrDefault()
According my Understanding If you want to Get objects that contain with specific parameter
then you can use this code
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
var SearchedValue= List1.where(x=>x.num==L1.num).tolist();
if you want just L1.num value then you can use this line (if searched record will 1 then you should use this)
var SearchedValue= List1.where(x=>x.num==L1.num).FirstOrDefault().num;
you can use
LIST1[index].propertyname //index is index of list element and propertyname is the name of property you want to access
I have a collection of string arrays (result of splitting CSV to rows and then delimiting)
{31001, 2014-01-01, 24:00:00},{31001, 2014-01-02, 24:00:00},{31001, 2014-01-03, 24:00:00} ...
Now I need to convert it to list of dictionaries, where each dictionary element will have custom key depending on arrays element index. So I want to achieve something like this:
{
{"Index":"31001", "Date":"2014-01-01", "Time":"24:00:00"},
{"Index":"31001", "Date":"2014-01-02", "Time":"24:00:00"},
{"Index":"31001", "Date":"2014-01-03", "Time":"24:00:00"},
...
}
I can't use models for this
Assuming you will have duplicate keys you could use something like
List<KeyValuePair<string,Tuple<string,string>>
where the key is the Index and the rest of the data belongs in the Tuple (Date,Time,..etc).
If you will have more data you couls simply use a List<KeyValuePair<string,List<string>>>
You could do it with an anonymous object.
this way would result in objList having all the rows with the properties Index,Date and Time. whilst not using named classes.
(please note I'm still learning if I don't name things right)
List<Object> objList = new List<object>();
foreach(var line in lines)
{
var fields = line.Split(',');
objList.Add(new {
Index = fields[0],
Date = fields[1],
Time=fields[2]
});
}
Beginner programmer here so please keep (explanation of) answers as simple as possible.
For an assignment we got a text file that contains a large amount of lines.
Each line is a different 'Order' with an ordernumber, location, frequency (amount of times per week), and a few other arguments.
Example:
18; New York; 3PWK; ***; ***; etc
I've made it so that each line is read and stored in a string with
string[] orders = System.IO.File.ReadAllLines(#<filepath here>);
And I've made a separate class called "Order" which has a get+set for all the properties like ordernumber, etc.
Now I'm stuck on how to actually get the values in there. I know how string splitting works but not how I can make unique objects in a loop.
I'd need something that created a new Order for every line and then assign Order.ordernumber, Order.location etc.
Any help would be MUCH appreciated!
An easy approach will be to make a class to define the orders like this:
public class Order{
public string OrderNumber{get;set;}
public string OrderId{get;set;}
public string OrderSomeThingElse{get;set;}
}
Then initialize a List:
var orderList = new List<Order>();
Then loop through and populate it:
foreach( var order in orders ){
var splitString = order.Split(';');
orderList.Add( new Order{
OrderNumber = splitString[0],
OrderId = splitString[1],
OrderSomeThingElse = splitString[2]
});
}
If you want an easy, but not that elegant approach, this is it.
In addition to all the good answers you've already received. I recommend you to use File.ReadLines() instead File.ReadAllLines() Because you are reading large file.
The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient. MSDN
Unless I misunderstand... do you mean something like this?
var ordersCollection = new List<Order>();
foreach (var order in orders)
{
var o = new Order();
o.PropertyName = ""; // Assign your property values like this
ordersCollection.Add(o);
}
// ordersCollection is now full of your orders.
How do I make a generated Object name? For example:
ObjectEx "name" = new ObjectEx();
Edit:
The object will be named by a user input.
The code will be:
Console.Write("Input new user's name: ");
string newUsersName = Console.ReadLine();
(Create ObjectEx)
Edit2:
I have a Dictionary for ObjectEx(Person) which handles all ObjectExs.
Person is the real class name, sorry about making the example object ObjectEx.
public static List<Person> persons = new List<Person>();
Objects don't have names - variables do, and they're always determined at compile-time.
If you want a map from string to object, just use a Dictionary<string, ObjectEx> - then come with random strings using Random. (There are plenty of examples of generating random strings on Stack Overflow.)
If you just want a collection of objects and you were using "random name" as a way of expressing that, use List<ObjectEx> - you don't need a name at all in that case.
If you need something else, please be more specific.
You can use array and store object in to that.
ObjectEx []arrObjectEx = new ObjectEx[10];
arrObjectEx[0] = new ObjectEx();
I would use list<T> (generic list) instead of array if the number of random elements are unknown.
List<ObjectEx> lstObjectEx = new List<ObjectEx>();
lstObjectEx.Add(new ObjectEx());
If randomly generated object need to be accessed uniquely then you can use dictionary. e.g
Dictionary<int, ObjectEx> dicObjectEx = new Dictionary<int, ObjectEx>();
dicObjectEx.Add(someUniqueNumber, new ObjectEx());
That is not possible but how about using a Dictionary. You can use a string value Add and Get hold of an Object you stored.
// somewhere near the start in your code initialize the dictionary
var dict = new Dictionary<string, Person>();
// later on you can dynamically add an Object to the Dictionary
// newUsersName is the so called Index
string newUsersName = Console.ReadLine();
dict.Add(newUsersName, new Person());
// if you need to get hold of that object again use the Index
// myObj is a Person type
var myObj = dict[newUsersName];
// assume Person has an Age property
myObj.Age = 20;
// show all Persons now in the dictionary
foreach(var username in dict.Keys)
{
Console.WriteLine(username);
var pers = dict[username];
Console.WriteLine("{0} is {1} years old", username, pers.Age );
}
You could use a dictionary to store objects, where the Key is the object name
I have dimensional list:
List<List<string>> index_en_bg = new List<List<string>>();
index_en_bg.Add(new List<string>() { word1, translation1 });
index_en_bg.Add(new List<string>() { word2, translation2 });
index_en_bg.Add(new List<string>() { word3, translation3 });
I would do binary search by the first column (words), something like this:
int row = index_en_bg.BinarySearch(searchingstr);
but it works only for a one-dimensional list. How would I extend it to work for two-dimensional lists in my case? I don't want to use Dictionary class.
In this case you need to provide your own customer IComparer-implementing comparator
public class Comparer: IComparer<IList<string>>
{
public int Compare(IList<string> x, IList<string> y)
{
// base the comparison result on the first element in the respective lists
// eg basically
return x[0].CompareTo(y[0]);
}
And you'll call it like this, offering a List where only the field you're searching is filled in.
int row = index_en_bg.BinarySearch(new List<string>() {searchingstr},new Comparer());
Well as far as I understand you should use Dictionary<K,V> instead, this way:
// 1 creating the dictionary
var dic = new Dictionary<string, string>();
dic["word1"] = "translation1";
dic["word2"] = "translation2";
dic["word3"] = "translation3";
// 2 finding a translation
var trans = dic["word1"];
And Dictionary<K,V> is really performant.
But if you insist on using BinarySearch you can implement IComparer<List<string>> and pass it to the function.
As you always search using the first item of the list you could use dictionary too.
var d = Dictionary<string, List<string>>();
as answered previously it's preforms much better than List.