How can show my list and make it searchable? C# - c#

Ok, i'm super new to this and this is for a schoolproject.
The project is to code a program where a person can store, update and search information.
In my program i make lists which store cloth information (brand, type, color, size) and i think my information gets stored but i don't know how access it / make a search function for it.
Is my code correct? Should i use another strategy?
This is where my list is defined(?!)
public class klädDATALIST
{
public string märke;
public string typ;
public string färg;
public string storlek;
public klädDATALIST(string _märke, string _typ, string _färg, string _storlek)
{
this.märke = _märke;
this.typ = _typ;
this.färg = _färg;
this.storlek = _storlek;
}
}
This is wehre the string variabels will be filled through a couple of Readline() functions.
For exampel:
string _färg = Console.ReadLine().ToUpper();
Then after i've saved it ill make a new list, i think?:
List<klädDATALIST> newklädDataList = new List<klädDATALIST>();
newklädDataList.Add(new klädDATALIST(_märke, _typ, _färg, _storlek));
I hope you can help me, thank you!

Elements can be accessed by iterating through the collection/List.
foreach( var item in newklädDataList)
{
// access or read item members.
Console.WriteLine(item.märke);
}
When you want to find an element in the List, you can either use Linq
var item = newklädDataList.FirstOrDefault(e=>e.märke == "searchstring"); //Any key to identify list item.
if(item != null)
{
Console.WriteLine(item.märke);
}
Or use Find
var item = newklädDataList.Find(e=>e.märke == "searchstring");
Hope this helps!

Related

c# and Lists: How do I use the foreach loop to retrieve the objects form my list?

this is quite the nooby questions, it's just that I havn't been doing this for a long time and would need some help.
So here is the problem. I have this debug info on my list "lstfriendlist":
I simply put up a breakpoint in my activity, then clicked on my list and saw, that all my "friends" are brought to me on this list under "friendUsername".
I was able to retrieve a certain username via:
string temp = lstfriendList[11].friendUsername.ToString();
This returns "torben" on my string "temp".
Now I just forgot how to use the foreach loop to retrieve all objects in order from my list and then write them down. I'm sorry to bother you with this, but I simply forgot :(
I hope you can help me.
Thank you :)
You already have declared a variable of the type "Friend" in the foreach loop's head. Now you can access the properties of the current object by typing
foreach (Friend f in lstfriendList)
{
string temp = f.friendUsername;
}
To complete Sebastian Hofmann answer, you can use .OrderBy or .OrderByDescending to order on name or username
foreach (Friend f in lstfriendList.OrderBy(list => list.friendUsername))
{
string temp = f.friendUsername;
}
Will return user name from a to z
foreach (Friend f in lstfriendList.OrderByDescending(list => list.friendUsername))
{
string temp = f.friendUsername;
}
Will return username z to a
I think there is no way to stuck there, since you are now having the Friend object(f) with you inside the loop, just place a . after f and see what intellisense suggests, Anyway It is pretty good if you modify the class like the following, with override ToString():
class Friend
{
public string friendUsername { get; set; }
public int friendId { get; set; }
// Add rest of properties here
public override string ToString()
{
return "ID :" + friendId + "\n Friend Name: " + friendUsername;
// Append rest of properties here
}
}
And then use like this:
foreach (Friend f in lstfriendList)
{
string friendDetails = f.ToString();
Console.WriteLine(friendDetails);
}

Deleting an array element while moving others down?

I'm really new to programming, so take this with a grain of salt.
I've made 2 arrays that correspond to eachother; One is a Name array and one is a Phone Number array. The idea is that the spot [1] in NameArray corresponds to spot [1] in the PhoneArray. In other words, I need to keep these 'pairings' in tact.
I'm trying to make a function that deletes one of the spots in the array, and shifts everything down one, as to fill the space left empty by the deleted element.
namearray = namearray.Where(f => f != iNum).ToArray();
is what I've tried, with iNum being the number corresponding to the element marked for deletion in the array.
I've also tried converting it to a list, removing the item, then array-ing it again.
var namelist = namearray.ToList();
var phonelist = phonearray.ToList();
namelist.Remove(txtName.Text);
phonelist.Remove(txtPhone.Text);
namearray = namelist.ToArray();
phonearray = phonelist.ToArray();
lbName.Items.Clear();
lbPhone.Items.Clear();
lbName.Items.AddRange(namearray);
lbPhone.Items.AddRange(phonearray);
with txtName.Text and txtPhone.Text being the strings for deletion in the corresponding list boxes.
Can someone suggest a better way to do it / What I'm doing wrong / How to fix?
Thanks guys
-Zack
A better way would be to have an array of a class that contains a Name and Phone Number object:
public class PersonData
{
public string Name { get; set; }
public string Phone { get; set; }
}
public PersonData[] data;
That way, instead of keeping two arrays in sync, it's one array with all the appropriate data.
Try a loop through both arrays, moving the values of each down an index each time.
Start the loop at the index of the value you want to delete. So you would find the IndexOf(T) the value you want, storing it as deleteIndex and run the loop starting from that index.
When you hit the end of the array, set the last value as null or string.Empty (depending what value type the array holds).
A bit like this:
var deleteIndex = namearray.IndexOf("TheStringYouWantToDelete");
for (int i = deleteIndex; i < namearray.Length; i++)
{
if (i == namearray.Length - 1) // The "last" item in the array.
{
namearray[i] = string.Empty; // Or null, or your chosen "empty" value.
phonearray[i] = string.Empty; // Or null, or your chosen "empty" value.
}
else
{
namearray[i] = namearray[i+1];
phonearray[i] = phonearray[i+1];
}
}
This will work for deleting and moving values 'down' in index.
You could also rewrite the code for moving them the other way, as it would work similarly.
Reordering them completely? Different ball game...
Hope this helps.
If the namearray and phonearray contain strings and you know the index of the element to remove (iNum) then you need to use the overload of the Where extension that takes a second parameter, the index of the current element in the evaluation
namearray = namearray.Where((x, y) => y != iNum).ToArray();
However the suggestion to use classes for your task is the correct one. Namearray and Phonearray (and whatever else you need to handle in future) are to be thought as properties of a Person class and instead of using arrays use a List<Person>
public class Person
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string Phone {get; set;}
}
List<Person> people = new List<Person>()
{
{new Person() {FirstName="Steve", LastName="OHara", Phone="123456"}},
{new Person() {FirstName="Mark", LastName="Noname", Phone="789012"}}
};
In this scenarion removing an item knowing the LastName could be written as
people = people.Where(x => x.LastName != "OHara").ToList();
(or as before using the index in the list of the element to remove)
people = people.Where((x, y) => y != iNum).ToArray();
The other answers provide some better design suggestions, but if you're using ListBoxes and want to stick with arrays, you can do this to synchronize them:
int idx = lbName.Items.IndexOf(txtName.Text);
if (idx > -1)
{
lbName.Items.RemoveAt(idx);
lbPhone.Items.RemoveAt(idx);
}
namearray = lbName.Items.Cast<string>().ToArray<string>();
phonearray = lbPhone.Items.Cast<string>().ToArray<string>();
Use a dictionary instead.
Dictionary<string, string> phoneBook = new Dictionary<string, string>();
phoneBook["Foo"] = "1234567890";
phoneBook["Bar"] = "0987654321";
phoneBook.Remove("Bar");

Get a single element of CSV file

I'm trying to add some csv elements to a list of Alimento, where Alimento is declared as:
namespace ContaCarboidrati
{
class Alimento
{
public virtual string Codice { get; set; }
public virtual string Descrizione { get; set; }
public virtual int Carboidrati { get; set; }
}
}
My csv looks something like this:
"C00, Pasta, 75".
Here's the method that should create the list from the csv:
private static List<Alimento> CreaListaAlimentiDaCsv()
{
List<Alimento> listaCsv = new List<Alimento>();
StreamReader sr = new StreamReader(#"C:\Users\Alex\Documents\RecordAlimenti.csv");
string abc = sr.ReadLine();
//listaCsv = abc.Split(",");
}
abc is "C00, Pasta, 75". I want to get a single element to add it to the list, or add all the 3 elements to the list, i thought that a single element is easier to made.
Sorry for my bad English
Thanks in advance
Alex
You are on the right track, but you cannot just create an Alimento of three strings, which is what you will get if you do abc.Split(","). You need to create a new Alimento object for each item (line) in the csv file and initialize each object correctly. Something like this:
var item = abc.Split(',');
listaCsv.Add(new Alimento() { Codice = item[0], Descrizione = item[1],
Carboidrati = int.Parse(item[2])};
Also, your csv seems to include spaces after the commas which you might want to get rid of. You could use string.Trim() to get rid of leading/trailing spaces. You also have to make sure the third item is actually an integer and take action if that is not the case (i.e. add some error handling).
As a side note, implementing a csv reader is not as trivial as one may think, but there are several free C# implementations out there. If you need something a bit more advanced than just reading a simple (and strictly one-line-per-item) csv, try one of these:
http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
http://www.filehelpers.com/
You can parse file with LINQ
var listaCsv = (from line in File.ReadAllLines("RecordAlimenti.csv")
let items = line.Split(',')
select new Alimento {
Codice = items[0],
Descrizione = items[1],
Carboidrati = Int32.Parse(items[2])
}).ToList();
You can parse it pretty easy assuming your data isn't bad.
private IEnumerable<Alimento> CreaListaAlimentiDaCsv(string fileName)
{
return File.Readlines(fileName) //#"C:\Users\Alex\Documents\RecordAlimenti.csv"
.Select(line => line.Split(',').Trim())
.Select(
values =>
new Alimento
{
Codice = value[0],
Descrizione = values[0],
Carboidrati = Convert.ToInt32(values[3])
});
}
You can also use Linq on the method such as
//Takes one line without iterating the entire file
CreaListaAlimentiDaCsv(#"C:\Users\Alex\Documents\RecordAlimenti.csv").Take(1);
//Skips the first line and takes the second line reading two lines total
CreaListaAlimentiDaCsv(#"C:\Users\Alex\Documents\RecordAlimenti.csv").Skip(1).Take(1);

how to add values in array

i just want to ask help again. I've created a method to read values in gridview, i was able to get and read values from the gridview. The problem now, is how can i store the values inside an array and i want it to pass on the other page.
here's the code i've created
private void getrowvalues()
{
string combinedvalues;
foreach (GridViewRow row in gvOrderProducts.Rows)
{
string prodname = ((Label)row.FindControl("lblProductName")).Text;
string txtvalues = ((TextBox)row.FindControl("txtQuantity")).Text;
combinedvalues = prodname + "|" + txtvalues;
}
}
i want the result string combinedvalues to be put in an array or collection of strings which i can be access in other page. Is there a way to do it? Any inputs will be greatly appreciated.
thanks!!
Just saw KroaX answer which is the same, I leave mine for the example code.
private void getrowvalues()
{
string combinedvalues;
List<string> combinedValuesList = new List<string>();
foreach (GridViewRow row in gvOrderProducts.Rows)
{
string prodname = ((Label)row.FindControl("lblProductName")).Text;
string txtvalues = ((TextBox)row.FindControl("txtQuantity")).Text;
combinedvalues = prodname + "|" + txtvalues;
combinedValuesList.Add(combinedvalues);
}
// use combinedValuesList or combinedValuesList.ToArray()
}
Notepad code, untested...
To pass something from one page to another, you can store it in the session (sometimes it depends).
Session["combinedvalueList"] = combinedvalueList;
While in another page, you can access it.
if (Session["combinedvalueList"]!=null)
combinedValueList = Session["combinedvalueList"] as List<string>;
//Before Foreach
List<string> combinedvalueList = new List<string>();
//Inside Foreach
combinedvalueList.add(combinedvalues);
Please also see
List MSDN
There you can see samples and Methods of List class. It seems to me you are completely new to c# and programming in general ?

CSharp .NET 3.5 Windows Form DataBinding ComboBox to a List<>

Ok, firstly I have the following code working.. although my question is this; should I code the combobox databinding like the following example, or is there an easier/more efficient way?
Firstly, I needed to manipulate the results back from the database to show a more descriptive meaning:
(I am using a basic class for the key/value pair)
class WashBayDesc
{
public string Key { get; set; }
public string Text { get; set; }
}
Now I retrieve the data from a datareader and do the manipulation I need which then adds the results to a list item:
var washbaydata = new List<WashBayDesc>();
// Read through the available cashboxes and populate a list/combobox
while (rdr.Read())
{
string sWashBayDesc = null;
string sWB = rdr["washbay"].ToString();
if (sWB.StartsWith("3"))
{
sWashBayDesc = "Bay " + sWB.Substring(1);
}
else
{
sWashBayDesc = "Auto " + sWB.Substring(1);
}
washbaydata.Add(new WashBayDesc { Key = sWB, Text = sWashBayDesc });
}
// Now bind the hashtable (with our bay selectors) to the dropdown
cmbCashBoxes.DataSource = washbaydata;
cmbCashBoxes.ValueMember = "Key";
cmbCashBoxes.DisplayMember = "Text";
So.. the idea is I can simply bind the ComboBox datasource to the washbaydata list object.. this works fine.
The next part is to retrieve the selected item value (i.e. not the textual description, but the value or key itself). This is the bit I think maybe doesn't quite look right, although again it works...
WashBayDesc myRes = new WashBayDesc();
myRes = (WashBayDesc)cmbCashBoxes.SelectedItem;
string sWashBayCashBox = myRes.Key;
So the result is my string sWashBayCashBox has the selected key...
I guess it works, and that is fine, but is there an easier/more cleaner way?
string sWashBayCashBox = (string)cmbCashBoxes.SelectedValue;

Categories

Resources