Hi i have this structure of txt file:
Lukas 1
Zdenek 3
Martin 2
Kate 1
And i need load this data...the name i need load to comboBox...and when i choose from ComboBox for example Lukas, i need to save Name Lukas to variable Name and number 1 to variable Number...
It is possible?
I have this code now...
using (StreamReader reader = new StreamReader(#"C:\Us...nka\example.txt"))
{
string data = "";
data = reader.ReadToEnd().Trim();
}
But i need read separately Name and separately Number...Have you any ideas? Thanks..
You can use File.ReadLines and String.Split:
var lines = File.ReadLines(#"C:\Us...nka\example.txt");
var data = lines.Select(l => l.Split());
I would use a class to store both properties:
public class Person
{
public int PersonID { get; set; }
public string PersonName { get; set; }
}
Now you can load the persons in a loop or with LINQ:
List<Person> allPersons = data
.Where(arr => arr.Length >= 2 && arr[1].Trim().All(Char.IsDigit))
.Select(arr => new Person
{
PersonName = arr[0].Trim(),
PersonID = int.Parse(arr[1].Trim())
})
.ToList();
Edit:
Yes thanks...but i cant load PersonsName to combobox
You can use a BindingSource for the ComboBox. Then set the DisplayMember and ValueMember properties accordingly:
var bindingSourcePersons = new BindingSource();
bindingSourcePersons.DataSource = allPersons;
personComboBox.DataSource = bindingSourcePersons.DataSource;
personComboBox.ValueMember = "PersonID";
personComboBox.DisplayMember = "PersonName";
First create a class like this:
public class Person {
public string Name {get;set;}
public int Number {get;set;}
}
then you can use Linq to convert the string you read like this:
var people = data
.Split(new {'\r','\n'}, StringSplitOptions.RemoveEmptyEntries)
.Select(d => new Person { Name = d.Split(' ')[0], Value = int.Parse(d.Split(' ')[1])})
.ToList();
Or better you could read your data line by line, like this:
var people = from l in File.ReadLines(#"C:\Us...nka\example.txt")
let parts = l.Split(' ')
select new Person {
Name = parts[0].Trim(),
Value = int.Parse(parts[1].Trim())
};
here is a pseudo:
while the reader is not EndOfStream
read current line
split the line that was just read into a string[] array, the separator being a space
first item in the array would be the name and the second item in the array would be the number.
then you add the item in the combo box. The combobox has an Items collection and an add method, which just takes a System.Object.
http://msdn.microsoft.com/en-us/library/aa983551(v=vs.71).aspx
Related
I have a problem with C#.
I managed it to parse out the price of a material from a web page (with a list of materials and prices) but I don't know exactly how I can extract single values to single strings or ints. I have assigned the "price" to a string but it this string contains a array of values.
Here's the C# Code:
var products = htmlDocument.DocumentNode.Descendants("div")
.Where(node => node.GetAttributeValue("id", "")
.Equals("accordion1")).ToList();
var productListItems = products[0].Descendants("tr")
.Where(node => node.GetAttributeValue("data-name", "")
.Contains("")).ToList();
foreach (var productListItem in productListItems)
{
Console.WriteLine(productListItem.GetAttributeValue("data-name", ""));
var tds = productListItem.Descendants("td").ToList();
var name = tds[0].InnerText;
var price = tds[1].InnerText.Trim('$');
Console.WriteLine(name);
Console.WriteLine(price);
}
Console:
clay_r
Lehm
199
coal_r
Kohle
427
copper_r
Kupfer
312
etc.
Now I want, that I can call a single material (like clay) with a single string. So that I have for every materialPrice a int.
Something like:
int clayPrice = int.Parse(the first price)
int coalPrice = int.Parse(the second price)
int copperPrice = int.Parse(the third price)
etc.
I'm pretty new to C#, so I don't know much about it. I hope someone understands my problem and can help me.
Define a separate class that contains the pricing information.
For example:
public class PriceInfo
{
public string Name {get; set;}
public string RawPrice {get; set;}
public int Price => int.Parse(RawPrice.Trim('$'));
}
Define a Dictionary as a class member. Dictionary.
Dictionary<string, PriceInfo> priceData = new Dictionary<string, PriceInfo>();
In your loop, add the prices to the dictionary.
foreach (var productListItem in productListItems)
{
Console.WriteLine(productListItem.GetAttributeValue("data-name", ""));
var tds = productListItem.Descendants("td").ToList();
var name = tds[0].InnerText;
var price = tds[1].InnerText;
// add to Dictionary
priceData[name] = new PriceInfo
{
Name = name,
RawPrice = price
};
}
Use the value:
priceData["somename"].Price
I have example data like this , the data is in the text file(.txt) sry i got this type of file, if its excel or csv maybe it will be easier
Edit : i make a console app with C#
FamilyID;name;gender;DOB;Place of birth;status
1;nicky;male;01-01-1998;greenland;married
1;sonia;female;02-02-1995;greenland;married
2;dicky;male;04-01-1995;bali;single
3;redding;male;01-05-1996;USA;single
3;sisca;female;05-03-1994;australia;married
i want to take the specific column from that data, for example i want to take FamilyID,Name and status.
I already tried some code to read data and take all the data and list it to new text file.
The goal is to create a new text file based on family ID, and only take specific columns.
The problem is : i cant take a specific column that i want from text file (don't know how to select many column in the code that i write)
DateTime date = DateTime.Now;
string tgl = date.Date.ToString("dd");
string bln = date.Month.ToString("d2");
string thn = date.Year.ToString();
string tglskrg = thn + "/" + bln + "/" + tgl;
string filename = ("C:\\Users\\Documents\\My Received Files\\exampledata.txt");
string[] liness = File.ReadAllLines(filename);
string[] col;
var lines = File.ReadAllLines(filename);
var groups = lines.Skip(1)
.Select(x => x.Split(';'))
.GroupBy(x => x[0]).ToArray();
foreach (var group in groups)
{
Console.WriteLine(group);
File.WriteAllLines(#"C:\\Users\\Documents\\My Received Files\\exampledata_"+group.Key+".txt", group.Select(x => string.Join(";", x)));
}
maybe someone can help? thankyou
One way to approach this would be capture the details to a data structure and later write the required details to file. For example,
public class Detail
{
public int FamilyID{get;set;}
public string Name{get;set;}
public string Gender{get;set;}
public DateTime DOB{get;set;}
public string PlaceOfBirth{get;set;}
public string Status{get;set;}
}
Now you can write a method that parses the string based on delimiter and returns an IEnumerable.
public IEnumerable<Detail> Parse(string source,char delimiter)
{
return source.Split(new []{Environment.NewLine},StringSplitOptions.RemoveEmptyEntries)
.Skip(1)
.Select(x=>
{
var detail = x.Split(new []{delimiter});
return new Detail
{
FamilyID = Int32.Parse(detail[0]),
Name = detail[1],
Gender = detail[2],
DOB = DateTime.Parse(detail[3]),
PlaceOfBirth = detail[4],
Status = detail[5]
};
}
);
}
Client Call
Parse(stringFromFile,';');
Output
Now you can pick and write the details you want to write to output file from the collection.
try this.
var list = new List<String>();
list.Add("FamilyID;name;gender;DOB;Place of birth;status");
list.Add("1;nicky;male;01-01-1998;greenland;married");
list.Add("1;sonia;female;02-02-1995;greenland;married");
list.Add("2;dicky;male;04-01-1995;bali;single");
list.Add("3;redding;male;01-05-1996;USA;single");
list.Add("3;sisca;female;05-03-1994;australia;married");
var group = from item in list.Skip(1)
let splitItem = item.Split(';', StringSplitOptions.RemoveEmptyEntries)
select new
{
FamilyID = splitItem[0],
Name = splitItem[1],
Status = splitItem[5],
};
foreach(var item in group.ToList())
{
Console.WriteLine($"Family ID: {item.FamilyID}, Name: {item.Name}, Status: {item.Status}");
}
I have a text file that contains product information on each line, in the form of "productCode,productName,amountInStock,etc.."
I've used File.ReadAllLines to store each line as an element in an array, and now I'm using those strings to assign values to a list of product structs.
Here is the code being used to split those strings from the array into substrings:
foreach (String line in readProducts)
{
productData = line.Split(',');
readProducts[foreachCount] = productData;
foreachCount++;
}
Which gives me this error in Visual Studio:
Cannot implicitly convert type 'string[]' to 'string'
What would be the best way to accomplish this task, assuming that I must use structs rather than classes?
Use this way
List<string[]> readProducts = new List<string[]>();
foreach (String line in readProducts)
{
productData = line.Split(',');
readProducts.Add(productData);
}
Here is a better option for you:
Let product be the class, contains properties such as productCode, productName,amountInStock,etc.. as you mentioned in the question. you can create a list of product and directly assign the input values to the list as like the following:
string path="path here"
List<product> ProductList = new List<product>();
foreach (string line in File.ReadAllLines(path))
{
string[] productDetails = line.Split(',');
ProductList.Add(new product() { productCode = productDetails[0], productName = productDetails[1] });
}
Where the Product class looks like:
public class product
{
public string productCode { get; set; }
public string productName { get; set; }
// rest of properties
}
You can use Select to project to a new collection:
var allItems = readProducts.Select(line => line.Split(',')); // collection of string arrays
or to project to a new type:
var allProducts = readProducts.Select(line => line.Split(',')) // collection of string arrays
.Select(array => new Product {
productCode = array[0],
productName = array[1],
amountInStock = array[2],
// etc.
}); // collection of Products
Using System and jagged arrays, I was able to solve the problem. Here is the code used in the working program.
int i = 0;
String[][] allProducts = new String[readProducts.Length][];
var parsedProduct = readProducts.Select(item => item.Split(','));
foreach (var item in parsedProduct)
{
allProducts[i] = item;
i++;
}
allProducts[][] is a jagged array. Otherwise known as an Array of Arrays.
parsedProduct is similar to the jagged array, each element contains another array with the substrings extracted from the current line of readProduct as their elements.
allProducts's elements are assigned the contents of parsedProducts's elements by the foreach loop.
As far as I can tell, there isn't any way to cut out the middle man and just use Select() on readProducts directly. But I could be wrong.
I has a string array declare as below
string[][] data = new string[3][];
string[] name = new string[10];
string[] contact = new string[10];
string[] address = new string[10];
After i fill the data to name, address and contact, the address can be empty string in some data. After that I assign it to string array data.
data[0] = name;
data[1] = contact;
data[2] = address
How I can sort the string array by name using LINQ. I try
data = data.orderby(y => y[0]).ToArray();
but this sort will change the sequence of the string array. Suppose data[0] is store name but after sorting it become store address.
Any one has idea how can I sort the record? Please help
You can use this to sort the name array (which is stored at data[0]):
data[0] = data[0].OrderBy(x => x).ToArray();
However, this will cause the data stored in the other arrays to loose any meaningful correlation to the name array (e.g. name[3] most likely will not match up with contact[3]). To avoid this,
I'd strongly recommend using a class to store this information:
class MyClass // TODO: come up with a better name
{
public string Name { get; set; }
public string Contact { get; set; }
public string Address { get; set; }
}
To declare the array, use:
MyClass[] data = new MyClass[10];
data[0] = new MyClass // Populate first record
{
Name = "...",
Contact = "...",
Address = "...",
};
And to sort the array:
data = data.OrderBy(x => x.Name).ToArray();
Or this:
Array.Sort(data, (x, y) => x.Name.CompareTo(y.Name));
The second option is more efficient as it rearranges the elements in place, and doesn't require allocating a new array to store the results.
Or alternatively, use a List<T>:
List<MyClass> data = new List<MyClass>(10);
data.Add(new MyClass // Populate first record
{
Name = "...",
Contact = "...",
Address = "...",
});
And to sort the list:
data.Sort((x, y) => x.Name.CompareTo(y.Name));
This will have similar performance to the Array.Sort method, however, it is a much better option if you need to be able to add or remove elements from your list dynamically.
I have list that have values like"
[0] = "{ id = ES10209005, views = 501 }"
[1] = "{ id = HYT0209005, views = 5678}"
[3] = "{ id = POI0209005, views = 4568}"
I would like to pass the values(id,views) to a method using a for each loop.
method(id,views)
Something like:
foreach (string v in updatereponse)
{
method()
}
How do I isolate each value(id,views) from each row in the list then pass it to the method?
The list contains just a bunch of strings, anything based on this to fix the problem would be just a workaround (e.g. string parsing). You should really switch to a strongly typed model, e.g. define a class ViewCount:
public class ViewCount
{
public string Id {get;set;}
public int Views {get;set;}
}
You can then use a List<ViewCount> populate the list:
List<ViewCount> viewcounts = new List<ViewCount>();
viewCounts.Add(new ViewCount() { Id = "ES10209005", Views = 501 });
Since each ViewCount instance has Id and Views properties you can now do the proper thing:
foreach (var item in updatereponse)
{
method(item.Id, item.Views);
}
If you are saving this data in a file, an alternative would be to use XML instead of custom strings, then you could use Linq to XML to populate a List<ViewCount>, e.g. using a simple XML like this:
<ViewCounts>
<ViewCount id="ES10209005" views="501" />
</ViewCounts>
You can then load your list:
XElement viewXml = XElement.Load("test.xml");
List<ViewCount> viewCounts = viewXml.Descendants("ViewCount")
.Select(x => new ViewCount()
{
Id = (string)x.Attribute("id"),
Views = (int)x.Attribute("views")
}).ToList();
foreach (string v in updateresponse)
{
var values = v.Split(",");
var id = values[0].Replace("{ id = ", "").Trim();
var view = values[1].Replace("views = ", "").("}","").Trim();
method(id, value);
}
Here's another way...you may want to add error checking:
String Data = "{ id = ES10209005, views = 501 }";
String[] Segments = Data.Split(new char[] { ' ', ',' });
string ID = Segments[3];
int views = int.Parse(Segments[7]);
Assuming the structure of your String is like you showed us always, this can work for you.
// First split id and views part.
String[] firstSplit = v.Split(',');
// Get the respected value for each part.
String id = firstSplit[0].Split('=')[1].Trim();
String views = firstSplit[1].Split('=')[1].Trim().Replace("}","");
You can use String methods to retrieve the items (use Split and SubString for example) or you can use a regular expression.
E.g.
var list = UpdateResponse[0].Split("=,} ") ;
will result in a list split by all these characters (including space).
Then check the correct indices to use (use a debugger for that). Then you get something like:
var id = list[5];
var views = list[8];
(note: check the indices 5 or 8, they are just a guess).