Reputation: 85
I'm trying to organize information in a text file and I thought a good way to do it would be to define each line of the file as its own List Item and then cut up each List entry by commas but I can't figure out how to parse or split the list items to use them later on.
This reads the file and returns a list with five entries:
public static List<String> ImportVehicalList() {
List<String> vehiclesAndOptions = new List<string>();
StreamReader sr = null;
try { // Attempt to open text file
String filePath = HttpContext.Current.Server.MapPath("~/srcDocuments/modelsAndOptions.txt");
String modelOptions; // Line to be added to List
using (sr = new StreamReader(filePath)) {
while ((modelOptions = sr.ReadLine()) != null) {
// Tried to split it before creating the list but
// this did not work.
//modelOptions.Split(',').ToList<String>();
vehiclesAndOptions.Add(modelOptions);
}
}
}
catch (Exception e) { } // File Not Found Catch
finally { try { sr.Close(); } catch (Exception ex) { } } // Cannot close the reader
return vehiclesAndOptions;
}
This is how I'm loading the list into an asp.net drop-down list. I was hoping to split the list here so that only the model shows in the drop down.
protected void Page_Load(object sender, EventArgs e) {
List<String> vehicalList = new List<string>();
vehicalList = Utils.ImportVehicalList();
foreach (String i in vehicalList) {
ddlModels.Items.Add(i);
//Response.Write(i);
}
// Binds the list to drop down menu ddlModels
//ddlModels.DataSource = vehicalList;
//ddlModels.DataBind();
}
There are a lot of post on here for parsing information and truthfully, I'm not very proficient with it and I have yet to find a solution that I am able to implement using my code. Here are some of the sources I've looked into:
How to split() a delimited string to a List<String>
https://www.dotnetperls.com/convert-list-string
Is it even possible to parse a list item on a comma or can this only be done by splitting a string first and then adding each item to a list?
Upvotes: 0
Views: 87
Reputation: 1453
I think what you are looking for is again string.split, when you are looping. So from what I understand, each line contains a model with attributes like so:
Model, attribute, attribute, attribute
And you want for each model a list of attributes. In your case this becomes:
string[] arr = vehicleAndoptions.Split(',');
string model = arr[0];// or arr.First(); if you prefer linq
List<string> attributes = arr.Skip(1).AsList<string>();
Upvotes: 1