i have a text file witch contains values like this :
0000000000
0000111222
0000144785
i need to insert this file into a HashTable with c#, this is what i've done so far :
string[] FileLines = File.ReadAllLines(#"D:TestHash.txt");
Hashtable hashtable = new Hashtable();
foreach (string line in FileLines)
{
// dont know what to do here
}
and after this i need to match a value from a textbox with the hashtable values. what should i do?
A Hashtable is a container for key-value-pairs. Since you only have values, not key-value-pairs, you don't need a hashtable, you need a HashSet:
HashSet<string> fileLineSet = new HashSet<string>(FileLines);
Check MSDN on how to use a hash set (including an example).
This reads all lines into a HashSet and checks the value of a TextBox against
HashSet<string> items = new HashSet<string>(File.ReadLines(#"D:\TestHash.txt"));
bool hasValue = items.Contains(TextBox.Text);
static void Main(string[] args)
{
string[] FileLines = File.ReadAllLines("your text file path");
Hashtable hashtable = new Hashtable();
foreach (string line in FileLines)
{
if (!hashtable.ContainsKey(line))
{
hashtable[line] = line;
}
}
foreach (var item in hashtable.Values)
{
//here you can match with your text box values...
//why you need to insert text file data into hash table really i dont know.from above foreach loop inside only you can match the values.might be you have some requirement for hash table i hope
string textboxVal = "text1";
if (item == textboxVal)
{
//both are matched.do your logic
}
else{
//not matched.
}
}
}
Related
with the following code Im trying to read a csv file that contains double values and convert it into a list. If I want to print that list The output just contains "system.collections.generic.list1 system.string". What is wrong in my code?
var filePath = #"C:\Users\amuenal\Desktop\Uni\test.csv";
var contents = File.ReadAllText(filePath).Split(';');
var csv = from line in contents
select line.Split(';').ToList();
foreach (var i in csv)
{
Console.WriteLine(i);
}
You got a couple things wrong with your code. First, you should most likely be using ReadAllLines() instead of ReadAllText(). Secondly, your LINQ query was returning a List<List<string>> which I imagine is not what you wanted. I would try something like this:
var filePath = #"C:\Users\amuenal\Desktop\Uni\test.csv";
//iterate through all the rows
foreach (var row in File.ReadAllLines(filePath))
{
//iterate through each column in each row
foreach(var col in row.Split(';'))
{
Console.WriteLine(col);
}
}
This should do good. Hope this helps.
var filePath = #"C:\Users\amuenal\Desktop\Uni\test.csv";
var contents = File.ReadAllLines(filePath);
var csv = (from line in contents
select line.Split(';')).SelectMany(x1 => x1);
foreach (var i in csv)
{
Console.WriteLine(i);
}
csv is an IEnumerable of a List of string. (in other words, each "i" is a list of string).
You need two loops:
foreach (var list in csv)
{
foreach(var str in list)
{
Console.WriteLine(str);
}
}
I've been trying to figure out how to remove elements in my ArrayList where the value contains some text string.
My Array could look like this:
[0] "\"MAERSKA.CO\",N/A,N/A,N/A,N/A,N/A,N/A"
[1] "\"GEN.COABB.ST\",N/A,N/A,N/A,N/A,N/A,N/A"
[2] "\"ARCM.ST\",\"Arcam AB\",330.00,330.50,332.00,330.50,330.00"
And my ArrayList is created like this:
string stringToRemove = "NA";
ArrayList rows = new ArrayList(csvData.Replace("\r", "").Split('\n'));
So the question is how I delete all entries that contains "NA".
I have tried the RemoveAt or RemoveAll with several combinations of Contains but i cant seem to get the code right.
I do not want to make a new Array if it can be avoided.
Regards
Flemming
If you want to reduce your ArrayList before instantiate your variable, consider using LINQ:
ArrayList rows = new ArrayList(csvData.Replace("\r", "").Split('\n').Where(r => !r.Contains(stringToRemove)).ToList());
If you want to reduce your ArrayList after instantiation, you can try this:
for (int i = 0; i < rows.Count; i++)
{
var row = (string)rows[i];
if (row.Contains(stringToRemove))
{
rows.RemoveAt(i);
i--;
}
}
The following code creates a list as output containing all strings except "N/A":
var outputs = new List<string>();
foreach (var item in input)
{
var splitted = item.Split(',');
foreach (var splt in splitted)
{
if (splt != "N/A")
{
outputs.Add(splt);
}
}
}
The input is your array.
Trying to read a csv file, and take the first word in the stream, throw it in to a dictionary while the following words get added to a list in that dictionary.
However, I find that (during debugging) when, inside my loop I decide to clear my list, all of the values it had added to the dictionary previously also get cleared. I guess I am mistaken in assuming it makes a copy of the list, it is actually just referencing that same list? Should I be creating a new list with every iteration? Code below:
public class TestScript : MonoBehaviour {
// Use this for initialization
void Start() {
Dictionary<string, List<string>> theDatabase = new Dictionary<string, List<string>>();
string word;
string delimStr = ",.:";
char[] delimiter = delimStr.ToCharArray();
List<string> theList = new List<string>();
using (StreamReader reader = new StreamReader("testComma.csv")) {
while (true) {
//Begin reading lines
string line = reader.ReadLine();
if (line == null) {
break;
}
//Begin splitting lines, adding to array.
string[] split2 = line.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
//Loop to hold the first word in the stream
for(int i = 0; i <= 0; i++) {
word = split2[i];
//loop to hold the following words in to list.
for (int y = 1; y < split2.Length; y++) {
theList.Add(split2[y]);
}
//Add word/list combo in to the database
theDatabase.Add(word, theList);
//clear the list.
theList.Clear();
}
}
}
foreach (KeyValuePair<string, List<string>> pair in theDatabase) {
string keys;
List<string> values;
keys = pair.Key;
values = pair.Value;
print(keys + " = " + values);
}
}
}
The bottom foreach loop is just so I can see the results. Also, any critique is welcome in regards to how this is written, as I'm a beginner.
Yes, you're adding the same object to your dictionary.
You can just change :
theDatabase.Add(word, theList);
To :
theDatabase.Add(word, theList.ToList());
Method ToList() makes shallow copy of your List<T>
C# is pass by reference.
So, theList and the list in your Dictionary are the same object.
The simplest solution is to stop clearing your List and create a new one every time instead:
for(int i = 0; i <= 0; i++) {
List<string> theList = new List<string>(); // it is in a loop now
word = split2[i];
//loop to hold the following words in to list.
for (int y = 1; y < split2.Length; y++) {
theList.Add(split2[y]);
}
//Add word/list combo in to the database
theDatabase.Add(word, theList);
//clear the list.
//theList.Clear(); - not required anymore
}
It is more readable and clear solution: create a list, insert items, paste a list into the dictionary, continue the iteration.
It is also much more performant since there is no List clearing - List<T>.Clear() is a linear operation, which takes O(n) operations.
Yes, as everyone says, lists are reference types. You need to make a copy to avoid the .Clear() clearing all the lists.
You could always write your code like this:
void Start()
{
string delimStr = ",.:";
Dictionary<string, List<string>> theDatabase =
File
.ReadAllLines("testComma.csv")
.Select(line => line.Split(delimStr.ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(x => x[0], x => x.Skip(1).ToList());
/* foreach here */
}
}
This doesn't have the problem with the list references.
my code
private void m1()
{
List<string> list = new List<string>();
foreach (string str in Directory.GetFiles("a1"))
{
if (Path.GetExtension(str).Contains("txt")) -- get all txt file in a1 folder
{
list.Add(Path.GetFileNameWithoutExtension(str));
}
}
base.SuspendLayout();
this.Combobox_1.Items.AddRange(list.ToArray());
base.ResumeLayout();
}
but combobox cannot list txt file in folder a1
Please helpme.
i think there is no need to store values first in a list and then add to a combobox.
it can be done directly to a combobox.
i have replace relative path a1 to a real one to let you understand easily.
foreach (string str in Directory.GetFiles(#"D:\"))
{
if (System.IO.Path.GetExtension(str).Contains("txt"))
{
this.Combobox_1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(str));
}
}
I have a list of variable names, lets say:
List<string> list = new List<string>();
list.Add("size");
list.Add("width");
list.Add("name");
list.Add("zip");
and i have text controls with those exact names, is there a way to loop through the list and only display what the value of the text control that i am asking for, like lets say something like this:
foreach (string txtctl in list)
{
Response.Write(Request.Form[txtctl]);
}
When i run this code the value just displays blank. Any suggestions?
string str = "";
foreach (string item in list)
{
TextBox txt = (TextBox)Form.FindControl(item);
if (txt != null)
{
str += item+":"+ txt.Text+"<br>";
}
}
Response.Write(str);