I need to read a List that has two properties, one is an ID int, the other is string.
After I get the values into the list I don't know how to break them down to the the IDs and name string one by one.
This is what I've got:
private async void UpdatePisterosLocal(List<Pisteros> PisterosLista)
{
try
{
PisterosDBController pistDB = new PisterosDBController();
Pisteros_Local pistLocal = new Pisteros_Local();
//this is my code trying to read the list PisterosLista
foreach (string element in PisterosLista)
{
pistLocal.IDPistero = //don't know what to write here
pistLocal.PisteroN = //and here
}
}
catch (Exception ex)
{
throw ex;
}
}
This how I finally did it
foreach (var item in PisterosLista)
{
var DatosRegistro = new T_Pisteros
{
PisteroID = item.PisteroID,
PisteroN = item.PisteroN
};
var num = db.Insert(DatosRegistro); //insert into new DB
}
I have this code
public List<string> GetAllFilesFromFolder(string root, bool searchSubfolders)
{
Queue<string> folders = new Queue<string>();
List<string> files = new List<string>();
folders.Enqueue(root);
while (folders.Count != 0)
{
string currentFolder = folders.Dequeue();
try
{
string[] filesInCurrent = System.IO.Directory.GetFiles(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly);
files.AddRange(filesInCurrent);
}
catch
{
// Do Nothing
}
try
{
if (searchSubfolders)
{
string[] foldersInCurrent = System.IO.Directory.GetDirectories(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly);
foreach (string _current in foldersInCurrent)
{
folders.Enqueue(_current);
}
}
}
catch
{
// Do Nothing
}
}
return files;
}
It list all files from especific directory and search for subdirectories ignoring excepetions to a List<string>
But How can I list the List<string> results to a listbox?
I tried to put
foreach (var foo in files)
{
listbox1.Items.Add(foo);
}
after return files; but for some reason the appears nothing in listbox... I am using visual basic windows forms
Try
listBox1.DataSource = MyList;
(duplicate: C#: easiest way to populate a ListBox from a List)
I am trying to split a string made of words, separated by the delimiter "-" and ",". The problem is that my program simply doesn't want to save anything in "var tokens". I already tried making "tokens" a string[], tried to use a char[] separator instead of putting "-" directly in the Split method, and tried the syntax "StringSplitOptions.RemoveEmptyEntries, but nothing works.
Here is my code:
if (!string.IsNullOrEmpty(destin) && string.IsNullOrEmpty(depar))
{
try
{
writer.WriteLine("SearchDest");
writer.WriteLine(destin);
string retur = reader.ReadLine();
Debug.WriteLine(retur);
var tokens = retur.Split('-');
flight.Clear();
foreach (string s in tokens)
{
Debug.WriteLine(s);
String[] flyelem = s.Split(',');
int idf = Convert.ToInt32(flyelem[0]);
String destf = flyelem[1];
String airf = flyelem[2];
int frees = Convert.ToInt32(flyelem[3]);
String datef = flyelem[4];
Flight b = new Flight(idf, destf, airf, frees, datef);
flight.Add(b);
}
dataGridView3.DataSource = null;
dataGridView3.Refresh();
dataGridView3.DataSource = flight;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The lines
string retur = reader.ReadLine();
Debug.WriteLine(retur);
will print: -6,Moscow,Domodedovo,30,4/3/2017 12:00:00 AM-7,Moscow,Vnukovo,30,4/3/2017 12:00:00 AM-9,Moscow,Vnukovo,40,4/3/2017 12:00:00 AM
and the line "Debug.WriteLine(s);" will always print nothing, just an empty space, the program stopping when it tries to parse the string to int at int idf.
How can I fix this problem and make split to work? Thank you.
EDIT:
Problem fixed. Tommy Naidich suggestion regarding using new[] {'-'} and Gunther Fox one of using StringSplitOptions.RemoveEmptyEntries as the second argument worked, and now the split works as intended. Final code for people who will encounter this problem in the future. Thank you guys.
if (!string.IsNullOrEmpty(destin) && string.IsNullOrEmpty(depar))
{
try
{
writer.WriteLine("SearchDest");
writer.WriteLine(destin);
string retur = reader.ReadLine();
Debug.WriteLine(retur);
string[] output = retur.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
flight.Clear();
foreach (string s in output)
{
Debug.WriteLine(s);
string[] flyelem = s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int idf = Convert.ToInt32(flyelem[0]);
string destf = flyelem[1];
string airf = flyelem[2];
int frees = Convert.ToInt32(flyelem[3]);
string datef = flyelem[4];
Flight b = new Flight(idf, destf, airf, frees, datef);
flight.Add(b);
}
dataGridView3.DataSource = null;
dataGridView3.Refresh();
dataGridView3.DataSource = flight;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Use the following syntax and change it to your desire.
string input = "-6,Moscow,Domodedovo,30,4/3/2017 12:00:00 AM-7,Moscow,Vnukovo,30,4/3/2017 12:00:00 AM-9,Moscow,Vnukovo,40,4/3/2017 12:00:00 AM";
string[] output = input.Split(new[] {'-', ','});
foreach(string s in output)
Console.WriteLine(s); // Will print each one of the split words.
Your main issue lies in not checking whether s is empty or not before trying to parse to an int. Adding the additional check before conversions means the loop will properly skip the first element in the array which is blank since your string begins with -.
Also, you were using String instead of string. Please see this answer as to why that's not advised.
You can also use int.TryParse instead of Convert.ToInt32 for some extra error checking.
Working dotnetfiddle
if (!string.IsNullOrEmpty(destin) && string.IsNullOrEmpty(depar))
{
try
{
writer.WriteLine("SearchDest");
writer.WriteLine(destin);
string retur = reader.ReadLine();
Debug.WriteLine(retur);
string[] tokens = retur.Split('-');
flight.Clear();
foreach (string s in tokens)
{
Debug.WriteLine(s);
if (!string.IsNullOrEmpty(s))
{
string[] flyelem = s.Split(',');
int idf;
int frees;
if (int.TryParse(flyelem[0], out idf) &&
int.TryParse(flyelem[3], out frees))
{
string destf = flyelem[1];
string airf = flyelem[2];
string datef = flyelem[4];
Flight b = new Flight(idf, destf, airf, frees, datef);
flight.Add(b);
}
}
}
dataGridView3.DataSource = null;
dataGridView3.Refresh();
dataGridView3.DataSource = flight;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I have a list of strings which holds file paths.
List<string> allFilesWithPathList = new List<string>();
allFilesWithPathList.Add(#"G:\Test\A.sql");
allFilesWithPathList.Add(#"G:\Test\B.sql");
allFilesWithPathList.Add(#"G:\Test\C.sql");
return allFilesWithPathList;
I have another list which holds a subset of files – but it has only the file name; not the path.
List<string> excludeList = new List<string>();
excludeList.Add("B.sql");
Now I need to get files from allFilesWithPathList that is not present in excludeList. Currently I am doing the following, using EXCEPT, after creating another list with file names only.
List<string> allFileNamesOnlyList = new List<string>();
foreach (string fileNameWithPath in allFilesWithPathList)
{
//Remove path and get only file name
int pos = fileNameWithPath.LastIndexOf(#"\") + 1;
string value = fileNameWithPath.Substring(pos, fileNameWithPath.Length - pos);
allFileNamesOnlyList.Add(value);
}
//EXCEPT logic
List<string> eligibleListToProcess = allFileNamesOnlyList.Except(excludeList).ToList();
What is the best way in LINQ to get this logic working without introducing another list like the above?
Note: I am using .Net 4.5
Complete code
class Program
{
static void Main(string[] args)
{
List<string> allFilesWithPathList = GetAllFilesWithPath();
List<string> excludeList = new List<string>();
excludeList.Add("B.sql");
List<string> allFileNamesOnlyList = new List<string>();
foreach (string fileNameWithPath in allFilesWithPathList)
{
//Remove path and get only file name
int pos = fileNameWithPath.LastIndexOf(#"\") + 1;
string value = fileNameWithPath.Substring(pos, fileNameWithPath.Length - pos);
allFileNamesOnlyList.Add(value);
}
//EXCEPT logic
List<string> eligibleListToProcess = allFileNamesOnlyList.Except(excludeList).ToList();
//Print all eligible files
foreach (string s in eligibleListToProcess)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
public static List<string> GetAllFilesWithPath()
{
List<string> allFilesWithPathList = new List<string>();
allFilesWithPathList.Add(#"G:\Test\A.sql");
allFilesWithPathList.Add(#"G:\Test\B.sql");
allFilesWithPathList.Add(#"G:\Test\C.sql");
return allFilesWithPathList;
}
}
allFilesWithPathList.Where(path => !allFileNamesOnlyList.Contains(Path.GetFileName(path));
There are two improvements here.
Path.GetFileName is much better than splitting the path yourself.
IEnumerable.Where in conjunction with ICollection.Contains to actually query the list in a succinct and easy to read way.
This should work
allFilesWithPathList.Where(x => !excludeList.Any(y => x.EndsWith(y)))
This is my first question here, so sorry for any wrong information or about my English.
I need to convert a List<Object> to List<Hashtable>
string IdsLista = string.Empty;
foreach (DataRow rows in ListaItensTransferencia.Rows)
{
IdsLista += Convert.ToString(rows["Id Bem"]) + ",";
}
string[] idsSelecionadosListaTransferencia = IdsLista.Split(',');
List<object> listaIdsSelecionadosListTransferencia = new List<object>(idsSelecionadosListaTransferencia.Length);
listaIdsSelecionadosListTransferencia.AddRange(idsSelecionadosListaTransferencia);
wuc_itensTransferencia.checkBoxGrid = listaIdsSelecionadosListTransferencia;
//v this is the list<hashtable> v this is the list<object>
wuc_itensTransferencia.ItensSelecionados = listaIdsSelecionadosListTransferencia;
How do I do this ?
Instead of putting data into list of object, put directly into list of hashtable. Why you want to create the comma separated string. Try this
List<HashTable> hashTable = new List<HashTable>();
foreach (DataRow rows in ListaItensTransferencia.Rows)
{
hashTable.Add(new HashTable("Id Bem", Convert.ToString(rows["Id Bem"])));
}