Searching a list C# - c#

Hope all is well.
I am struggling with a simple problem here. I am trying to create a console app that allows you to search for words in a list (by one or more characters ie u = user, user group).
I can't seem to get past this error:
Error CS0305 Using the generic type 'List' requires 1 type arguments wordSearch c:\Projects\wordSearch\wordSearch\Program.cs 36 Active
Please find my code below..... Any help is welcome Thank you in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace wordSearch
{
public class MyList<T> { }
public class TestList<T> { }
class MyList
{
public static void Main()
{
string searchKeyword = "o";
List<string> items = new List<string>();
items.Add("User");
items.Add("User Groups");
items.Add("User Activity Log");
items.Add("Report Designer");
items.Add("Report Activity Log");
List<string> searchResults = items.FindAll(u =>
u.Contains(searchKeyword));
Console.WriteLine("Please type in the first letter of item you
are looking for:");
Console.ReadLine();
foreach (var result in System.Collections.Generic.List.Where(u =>
u.IndexOf(mySearchString) == 0))
{
Console.WriteLine("User, User Groups, User Activity Log");
Console.ReadKey();
}
foreach (var result in List.Where(r => r.IndexOf(mySearchString) ==
0))
{
Console.WriteLine("Report Desinger, Report Activity Log");
Console.ReadKey();
}
}
}
}

There are two issues with your code:
You have to save user's input ("...the first letter user is looking for..."), e.g. in mySearchString which you've already used as filter.
You have to query and scan items instance, not System.Collections.Generic.ListList type:
You can put it like this:
...
Console.WriteLine("Please type in the first letter of item you are looking for:");
//DONE: user input saved
string mySearchString = Console.ReadLine();
//DONE: we scan items, not List
foreach (var result in items.Where(u => u.IndexOf(mySearchString) == 0)) {
Console.WriteLine("User, User Groups, User Activity Log");
Console.ReadKey();
}
// DONE: we scan items not List
foreach (var result in items.Where(r => r.IndexOf(mySearchString) == 0)) {
Console.WriteLine("Report Desinger, Report Activity Log");
Console.ReadKey();
}
...
Edit: It seems that the actual request is to query list in a loop, foreach not copy-pasting, something like this:
public static void Main() {
List<string> items = new List<string>() {
"User",
"User Groups",
"User Activity Log",
"Report Designer",
"Report Activity Log",
}
while (true) {
Console.WriteLine("Please type in the first letter of item you are looking for:");
Console.WriteLine("Prease press enter (i.e. type an empty string) to quit");
string mySearchString = Console.ReadLine();
if (string.IsNullOrEmpty(mySearchString))
break;
foreach (var item in items.Where(r => r.IndexOf(mySearchString) == 0))
Console.WriteLine(item);
Console.WriteLine();
}
}

Related

How to sort a List<string> based on the string after last index of the string c#

I'm wanting to be able to re-order a list based on the lastindexof a character in this case "/".
var ListToSort = new List<string> { "Hjgs/dasdf/ada/2toe0685tcr1/Hello_1",
"Hjgs/dasdf/ada/xdt42pj616ao/Yes_1",
"Hjgs/dasdf/ada/7yhzozo2rgu5/Hello_2",
"Hjgs/dasdf/ada/atrejl1rzliq/Yes_2",
"Hjgs/dasdf/ada/bgwq9i8fbsj4/Hello_3",
"Hjgs/dasdf/ada/4rrx4pldbiq1/Zues_1"};
im wanting to sort the list based on the last index of "/" eg it would compare Yes_1,Hello_2 and so on , the expected output would be:
Hjgs/dasdf/ada/2toe0685tcr1/Hello_1
Hjgs/dasdf/ada/7yhzozo2rgu5/Hello_2
Hjgs/dasdf/ada/bgwq9i8fbsj4/Hello_3
Hjgs/dasdf/ada/xdt42pj616ao/Yes_1
Hjgs/dasdf/ada/atrejl1rzliq/Yes_2
Hjgs/dasdf/ada/4rrx4pldbiq1/Zues_1
edit : working solution from comments
ListToSort = ListToSort.OrderBy(x => x.Substring(x.LastIndexOf("/"))).ToList();
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var ListToSort = new List<string> { "Hjgs/dasdf/ada/2toe0685tcr1/Hello_1",
"Hjgs/dasdf/ada/xdt42pj616ao/Yes_1",
"Hjgs/dasdf/ada/7yhzozo2rgu5/Hello_2",
"Hjgs/dasdf/ada/atrejl1rzliq/Yes_2",
"Hjgs/dasdf/ada/bgwq9i8fbsj4/Hello_3",
"Hjgs/dasdf/ada/4rrx4pldbiq1/Zues_1"};
foreach(var item in ListToSort.OrderBy(x => x.Substring(x.LastIndexOf("/"))))
Console.WriteLine(item);
}
}

C# Comparing an Input to a String Exactly

I have a list of most of the elements in the periodic table in order of their placement on the table:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chemistry_Element_Calculator
{
class Program
{
static void Main(string[] args)
{
// Declare all numbers
int electronNumber;
int protonNumber;
float neutronNumber;
int i;
// Declare all strings
string elementRequest;
// Create an list for all elements
List<string> elementNameList = new List<string>();
List<string> elementSymbolList = new List<string>();
// Add all elements to the list
elementNameList.Add("Hydrogen"); elementSymbolList.Add("H");
elementNameList.Add("Helium"); elementSymbolList.Add("He");
elementNameList.Add("Lithium"); elementSymbolList.Add("Li");
elementNameList.Add("Beryllium"); elementSymbolList.Add("Be");
elementNameList.Add("Boron"); elementSymbolList.Add("B");
elementNameList.Add("Carbon"); elementSymbolList.Add("C");
elementNameList.Add("Nitrogen"); elementSymbolList.Add("N");
elementNameList.Add("Oxygen"); elementSymbolList.Add("O");
elementNameList.Add("Fluorine"); elementSymbolList.Add("F");
elementNameList.Add("Neon"); elementSymbolList.Add("Ne");
elementNameList.Add("Sodium"); elementSymbolList.Add("Na");
elementNameList.Add("Magnesium"); elementSymbolList.Add("Mg");
elementNameList.Add("Aluminium"); elementSymbolList.Add("Al");
elementNameList.Add("Silicon"); elementSymbolList.Add("Si");
elementNameList.Add("Phosphorus"); elementSymbolList.Add("P");
elementNameList.Add("Sulfur"); elementSymbolList.Add("S");
elementNameList.Add("Chlorine"); elementSymbolList.Add("Cl");
elementNameList.Add("Argon"); elementSymbolList.Add("Ar");
elementNameList.Add("Potassium"); elementSymbolList.Add("K");
elementNameList.Add("Calcium"); elementSymbolList.Add("Ca");
elementNameList.Add("Scandium"); elementSymbolList.Add("Sc");
elementNameList.Add("Titanium"); elementSymbolList.Add("Ti");
elementNameList.Add("Vanadium"); elementSymbolList.Add("V");
elementNameList.Add("Chromium"); elementSymbolList.Add("Cr");
elementNameList.Add("Manganese"); elementSymbolList.Add("Mn");
elementNameList.Add("Iron"); elementSymbolList.Add("Fe");
elementNameList.Add("Cobalt"); elementSymbolList.Add("Co");
elementNameList.Add("Nickel"); elementSymbolList.Add("Ni");
elementNameList.Add("Copper"); elementSymbolList.Add("Cu");
elementNameList.Add("Zinc"); elementSymbolList.Add("Zn");
elementNameList.Add("Gallium"); elementSymbolList.Add("Ga");
elementNameList.Add("Germanium"); elementSymbolList.Add("Ge");
elementNameList.Add("Arsenic"); elementSymbolList.Add("As");
elementNameList.Add("Selenium"); elementSymbolList.Add("Se");
elementNameList.Add("Bromine"); elementSymbolList.Add("Br");
elementNameList.Add("Krypton"); elementSymbolList.Add("Kr");
elementNameList.Add("Rubidium"); elementSymbolList.Add("Rb");
elementNameList.Add("Strontium"); elementSymbolList.Add("Sr");
elementNameList.Add("Yttrium"); elementSymbolList.Add("Y");
elementNameList.Add("Zirconium"); elementSymbolList.Add("Zr");
elementNameList.Add("Niobium"); elementSymbolList.Add("Nb");
elementNameList.Add("Molybdenum"); elementSymbolList.Add("Mo");
elementNameList.Add("Technetium"); elementSymbolList.Add("Tc");
elementNameList.Add("Rubidium"); elementSymbolList.Add("Ru");
elementNameList.Add("Rhodium"); elementSymbolList.Add("Rh");
elementNameList.Add("Palladium"); elementSymbolList.Add("Pd");
elementNameList.Add("Silver"); elementSymbolList.Add("Ag");
elementNameList.Add("Cadmium"); elementSymbolList.Add("Cd");
elementNameList.Add("Indium"); elementSymbolList.Add("In");
elementNameList.Add("Tin"); elementSymbolList.Add("Sn");
elementNameList.Add("Antimony"); elementSymbolList.Add("Sb");
elementNameList.Add("Tellurium"); elementSymbolList.Add("Te");
elementNameList.Add("Iodine"); elementSymbolList.Add("I");
elementNameList.Add("Xenon"); elementSymbolList.Add("Xe");
elementNameList.Add("Caesium"); elementSymbolList.Add("Cs");
elementNameList.Add("Barium"); elementSymbolList.Add("Ba");
elementNameList.Add("Lanthanum"); elementSymbolList.Add("La");
elementNameList.Add("Cerium"); elementSymbolList.Add("Ce");
elementNameList.Add("Praseodynium"); elementSymbolList.Add("Pr");
elementNameList.Add("Neodymium"); elementSymbolList.Add("Nd");
elementNameList.Add("Promethium"); elementSymbolList.Add("Pm");
elementNameList.Add("Samarium"); elementSymbolList.Add("Sm");
elementNameList.Add("Europium"); elementSymbolList.Add("Eu");
elementNameList.Add("Gadolinium"); elementSymbolList.Add("Gd");
elementNameList.Add("Terbium"); elementSymbolList.Add("Tb");
elementNameList.Add("Dysprosium"); elementSymbolList.Add("Dy");
elementNameList.Add("Holomium"); elementSymbolList.Add("Ho");
elementNameList.Add("Erbium"); elementSymbolList.Add("Er");
elementNameList.Add("Thulium"); elementSymbolList.Add("Tm");
elementNameList.Add("Ytterbium"); elementSymbolList.Add("Yb");
elementNameList.Add("Lutenium"); elementSymbolList.Add("Lu");
elementNameList.Add("Hafnium"); elementSymbolList.Add("Hf");
elementNameList.Add("Tantalum"); elementSymbolList.Add("Ta");
elementNameList.Add("Tungsten"); elementSymbolList.Add("W");
elementNameList.Add("Rhenium"); elementSymbolList.Add("Re");
elementNameList.Add("Osmium"); elementSymbolList.Add("Os");
elementNameList.Add("Iridium"); elementSymbolList.Add("Ir");
elementNameList.Add("Platinum"); elementSymbolList.Add("Pt");
elementNameList.Add("Gold"); elementSymbolList.Add("Au");
elementNameList.Add("Mercury"); elementSymbolList.Add("Hg");
elementNameList.Add("Thallium"); elementSymbolList.Add("Tl");
elementNameList.Add("Lead"); elementSymbolList.Add("Pb");
elementNameList.Add("Bismuth"); elementSymbolList.Add("Bi");
elementNameList.Add("Polonium"); elementSymbolList.Add("Po");
elementNameList.Add("Astatine"); elementSymbolList.Add("At");
elementNameList.Add("Radon"); elementSymbolList.Add("Rn");
elementNameList.Add("Francium"); elementSymbolList.Add("Fr");
elementNameList.Add("Radium"); elementSymbolList.Add("Ra");
elementNameList.Add("Actinium"); elementSymbolList.Add("Ac");
elementNameList.Add("Thorium"); elementSymbolList.Add("Th");
elementNameList.Add("Palladium"); elementSymbolList.Add("Pa");
elementNameList.Add("Uranium"); elementSymbolList.Add("U");
elementNameList.Add("Nepturium"); elementSymbolList.Add("Np");
elementNameList.Add("Plutonium"); elementSymbolList.Add("Pu");
elementNameList.Add("Americium"); elementSymbolList.Add("Am");
elementNameList.Add("Curium"); elementSymbolList.Add("Cm");
elementNameList.Add("Berkelium"); elementSymbolList.Add("Bk");
elementNameList.Add("Californium"); elementSymbolList.Add("Cf");
elementNameList.Add("Einsteinium"); elementSymbolList.Add("Es");
elementNameList.Add("Fermium"); elementSymbolList.Add("Fermium");
elementNameList.Add("Mendelevium"); elementSymbolList.Add("Md");
elementNameList.Add("Nobelium"); elementSymbolList.Add("No");
elementNameList.Add("Lawrencium"); elementSymbolList.Add("Lr");
elementNameList.Add("Rutherfordium"); elementSymbolList.Add("Rf");
elementNameList.Add("Dubnium"); elementSymbolList.Add("Db");
elementNameList.Add("Seaborgium"); elementSymbolList.Add("Sg");
elementNameList.Add("Bohrium"); elementSymbolList.Add("Bh");
elementNameList.Add("Hassium"); elementSymbolList.Add("Hs");
elementNameList.Add("Meitnerium"); elementSymbolList.Add("Mt");
elementNameList.Add("Darmstadtium"); elementSymbolList.Add("Ds");
elementNameList.Add("Roentgenium"); elementSymbolList.Add("Rg");
elementNameList.Add("Copernicium"); elementSymbolList.Add("Cn");
Console.WriteLine("What element do you want? Either input it's full name, with a capital letter, or it's elemnent symbol. E.g. N for Nitrogen");
elementRequest = Console.ReadLine();
elementNameList.ForEach(delegate (String elementName)
{
if (elementRequest == elementName)
{
Console.WriteLine("Hydrogen");
}
else
{
Console.WriteLine("Not Hydrogen");
};
});
Console.Read();
However, when I run the program, and input Hydrogen, both Helium and Hydrogen are said to be hydrogen. How can I fix this?
Also, if anyone has an idea on how to compress the 2 lists so they're smaller, let me know :)
Thanks :)
What you want your code to do is take the index from the first list, and return the string at the same index in the second list.
Your code is currently not doing any of that, but always printing "Hydrogen", your output thus always being "Hydrogen" whatever element is requested.
You can trivially fix that by actually looking up the index:
int indexOfElementName = elementNameList.IndexOf(elementRequest);
string elementSymbol = elementSymbolList[indexOfElementName];
Note that that does not handle casing and requested elements that aren't in the list (or typos).
But keeping the two lists in sync, and this code in general, is a maintenance disaster waiting to happen.
Instead you could use a dictionary where the element name is the key and the symbol the value:
var elementDictionary = new Dictionary<string, string>
{
{ "Hydrogen", "H" },
{ "Helium", "He" },
// ...
}
Then look it up:
string elementSymbol = elementDictionary[elementRequest];
Do note that this still doesn't handle case-insensitivity and elements that are not found, but I'll leave that as an exercise to you.
I would use a custom class and a list as suggested by ElectricRouge.
I don't favor the dictionary because you need to search both by name and symbol. Also, the data set is small (118 elements to date).
See comments for the explanation of the code.
using System;
using System.Collections.Generic;
namespace Chemistry_Element_Calculator
{
// Create a chemical element class
// You can add more properties such as number of electrons, etc.
public class ChemicalElement
{
public string Symbol
{
get; set;
}
public string Name
{
get; set;
}
}
class Program
{
static void Main(string[] args)
{
// Create a list of the elements, populate their properties
var elements = new List<ChemicalElement>()
{
new ChemicalElement {Name = "Hydrogen", Symbol = "H"},
new ChemicalElement {Name = "Helium", Symbol = "He"},
new ChemicalElement {Name = "Lithium", Symbol = "Li"}
// etc.
};
Console.WriteLine("What element do you want? Either input it's full name, with a capital letter, or it's elemnent symbol. E.g. N for Nitrogen");
var elementRequest = Console.ReadLine();
// Use find to get a matching element, compare both name and symbol
var foundElement = elements.Find(element => element.Symbol == elementRequest || element.Name == elementRequest);
if (foundElement == null)
{
// Output if no element is found
Console.WriteLine("Element Not Found");
}
else
{
// Output if the element is found
Console.WriteLine("Found element {0}.", foundElement.Name);
}
Console.WriteLine("[Press any key to finish]");
Console.ReadKey();
}
}
}
The code uses the method List.Find to get the result, it will only return the first match.
I would also suggest to migrate to String.Compare if you want to have case-insensitive comparison.
And finally I would be reading the data form file or a database, but that is beyond the question.

Loading entries from a list made from .csv file

I am trying to retrieve data from a series of lists that have been populated from a single .csv file
i have the entire list added to a Dictionary and abbreviations from "lol" speak
so far i have it able to search through the list/dictionary and determine whether the item that is searched for is present or not. All i want to do it to write the:
abbreviation - full meaning
into the console
Here is my code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace expanded_meanings
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> lolspeak_dictionary = new Dictionary<string, string>();
var reader = new StreamReader(File.OpenRead(#"H:\twitter.csv"));
List<string> short_name = new List<string>();
List<string> longer_name = new List<string>();
int count=0;
string search = Console.ReadLine();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
lolspeak.Add(values[0], values[1]);
short_name.Add(values[0]);
longer_name.Add(values[1]);
count = count + 1;
}
if (short_name.Contains(search))
{
Console.WriteLine("Item found");
}
else
Console.WriteLine("Not Found");
Console.ReadLine();
}
//if (short_name = user_search);
}
}
First, you do not need the short_name and long_name as those values are contained within the lolspeak_dictionary, You can access them by using the Keys and Values properties of a Dictionary.
As for searching for the abbreviation - full meaning you can simply use your current code as
if (lolspeak_dictionary.ContainsKey(search))
{
Console.WriteLine("{0} - {1}", search, lolspeak_dictionary[search]);
}
else {
Console.WriteLine("'{0}' - Not Found", search);
}
UPDATE:
The method call Console.WriteLine("'{0}' - Not Found", search); works by using substitution. The value of search, is placed in the spot of {0}. The means that {0} - Not Found if search is WOTR you will get WOTR - Not found.
In the case of Console.WriteLine("{0} - {1}", search, lolspeak_dictionary[search]);. If search is WOTA, you would get WOTA - Will of the Ancients.
Additional Resources
Dictionary MSDN
Keys MSDN
Values MSDN
Understanding Dictionary

Appropriate datastructure for key.contains(x) Map/Dictionary

I am somewhat struggling with the terminology and complexity of my explanations here, feel free to edit it.
I have 1.000 - 20.000 objects. Each one can contain several name words (first, second, middle, last, title...) and normalized numbers(home, business...), email adresses or even physical adresses and spouse names.
I want to implement a search that enables users to freely combine word parts and number parts.When I search for "LL 676" I want to find all objects that contain any String with "LL" AND "676".
Currently I am iterating over every object and every objects property, split the searchString on " " and do a stringInstance.Contains(searchword).
This is too slow, so I am looking for a better solution.
What is the appropriate language agnostic data structure for this?
In my case I need it for C#.
Is the following data structure a good solution?
It's based on a HashMap/Dictionary.
At first I create a String that contains all name parts and phone numbers I want to look through, one example would be: "William Bill Henry Gates III 3. +436760000 billgatesstreet 12":
Then I split on " " and for every word x I create all possible substrings y that fullfill x.contains(y). I put every of those substrings inside the hashmap/dictionary.
On lookup/search I just need to call the search for every searchword and the join the results. Naturally, the lookup speed is blazingly fast (native Hashmap/Dictionary speed).
EDIT: Inserts are very fast as well (insignificant time) now that I use a smarter algorithm to get the substrings.
It's possible I've misunderstood your algorithm or requirement, but this seems like it could be a potential performance improvement:
foreach (string arg in searchWords)
{
if (String.IsNullOrEmpty(arg))
continue;
tempList = new List<T>();
if (dictionary.ContainsKey(arg))
foreach (T obj in dictionary[arg])
if (list.Contains(obj))
tempList.Add(obj);
list = new List<T>(tempList);
}
The idea is that you do the first search word separately before this, and only put all the subsequent words into the searchWords list.
That should allow you to remove your final foreach loop entirely. Results only stay in your list as long as they keep matching every searchWord, rather than initially having to pile everything that matches a single word in then filter them back out at the end.
In case anyone cares for my solution:
Disclaimer:
This is only a rough draft.
I have only done some synthetic testing and I have written a lot of it without testing it again.I have revised my code: Inserts are now ((n^2)/2)+(n/2) instead of 2^n-1 which is infinitely faster. Word length is now irrelevant.
namespace MegaHash
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
public class GenericConcurrentMegaHash<T>
{
// After doing a bulk add, call AwaitAll() to ensure all data was added!
private ConcurrentBag<Task> bag = new ConcurrentBag<Task>();
private ConcurrentDictionary<string, List<T>> dictionary = new ConcurrentDictionary<string, List<T>>();
// consider changing this to include for example '-'
public char[] splitChars;
public GenericConcurrentMegaHash()
: this(new char[] { ' ' })
{
}
public GenericConcurrentMegaHash(char[] splitChars)
{
this.splitChars = splitChars;
}
public void Add(string keyWords, T o)
{
keyWords = keyWords.ToUpper();
foreach (string keyWord in keyWords.Split(splitChars))
{
if (keyWord == null || keyWord.Length < 1)
return;
this.bag.Add(Task.Factory.StartNew(() => { AddInternal(keyWord, o); }));
}
}
public void AwaitAll()
{
lock (this.bag)
{
foreach (Task t in bag)
t.Wait();
this.bag = new ConcurrentBag<Task>();
}
}
private void AddInternal(string key, T y)
{
for (int i = 0; i < key.Length; i++)
{
for (int i2 = 0; i2 < i + 1; i2++)
{
string desire = key.Substring(i2, key.Length - i);
if (dictionary.ContainsKey(desire))
{
List<T> l = dictionary[desire];
lock (l)
{
try
{
if (!l.Contains(y))
l.Add(y);
}
catch (Exception ex)
{
ex.ToString();
}
}
}
else
{
List<T> l = new List<T>();
l.Add(y);
dictionary[desire] = l;
}
}
}
}
public IList<T> FulltextSearch(string searchString)
{
searchString = searchString.ToUpper();
List<T> list = new List<T>();
string[] searchWords = searchString.Split(splitChars);
foreach (string arg in searchWords)
{
if (arg == null || arg.Length < 1)
continue;
if (dictionary.ContainsKey(arg))
foreach (T obj in dictionary[arg])
if (!list.Contains(obj))
list.Add(obj);
}
List<T> returnList = new List<T>();
foreach (T o in list)
{
foreach (string arg in searchWords)
if (dictionary[arg] == null || !dictionary[arg].Contains(o))
goto BREAK;
returnList.Add(o);
BREAK:
continue;
}
return returnList;
}
}
}

Sorting information to output list

I'm new to programming and I thought it would be great to start with something a bit simple but useful for me and my girlfriend.
I would like to create a shopping list program that will take my items that I input into the textbox and then sort them based on defined groups. Then output that information in an easy to read list already categorized for easy shopping.
My question is this; How do I sort information that I put into a rich textbox? I have two rich textboxes and I would like to input information into one and then output that information to the other but have it sorted to my preferences.
Thank you in advance. :-)
Since you want to group them, I would suggest creating a small GroceryItem like this:
class GroceryItem
{
GroceryItem(string category, string name) {
Category = category;
ItemName = name;
}
public string Category {get;set;}
public string ItemName {get;set;}
}
Then you can easily parse from your first text box the items. Let's assume they look like this:
Vegies, Tomato
Meat, Lamb
Vegies, Potato
Meat, Chicken
Just read them all, split on , to get 2 parts for each, and create a new GroceryItem:
List<CategoryItem> shoppingList = new List<CategoryItem>();
foreach (var line in your_lines_collection)
{
var parts = some_line.Split(',');
shoppingList.Add(new GroceryITem(parts[0],parts[1]));
}
And last, but not least, once you have a list of those (shoppingList), you can use linq to sort to your heart content. Here's an example:
List<GroceryItem> shoppingList = new List<GroceryItem>();
List<string> groceries = new List<string>(){"veg, pot", "veg, tom", "meat, chicken", "meat, veal"};
foreach (var line in groceries)
{
var parts = line.Split(',');
shoppingList.Add(new GroceryItem(parts[0],parts[1]));
}
var sorted_list_by_ItemName =
from item in shoppingList
orderby item.ItemName
group item by item.Category into groups
select groups
;
foreach (var gr in sorted_list_by_ItemName)
{
Console.Out.WriteLine("[{0}] :", gr.Key);
foreach (var it in gr)
Console.Out.WriteLine(" {0}", it);
}
This will output:
[meat] :
meat , chicken
meat , veal
[veg] :
veg , pot
veg , tom
You then can just print this on your other textbox, or work with it as you wish :)
As per comments, here's the whole code for a console, just paste it into your visual studio, and it should work:
using System;
using System.Collections.Generic;
using System.Linq;
internal class Program
{
public static void Main(string[] args)
{
List<GroceryItem> shoppingList = new List<GroceryItem>();
List<string> groceries = new List<string>() { "veg, pot", "veg, tom", "meat, chicken", "meat, veal" };
foreach (var line in groceries)
{
var parts = line.Split(',');
shoppingList.Add(new GroceryItem(parts[0], parts[1]));
}
var sorted_list_by_ItemName =
from item in shoppingList
orderby item.ItemName
group item by item.Category into groups
select groups;
foreach (var gr in sorted_list_by_ItemName)
{
Console.Out.WriteLine("[{0}] :", gr.Key);
foreach (var it in gr)
Console.Out.WriteLine(" {0}", it);
}
Console.ReadKey();
}
public class GroceryItem
{
public GroceryItem(string category, string name)
{
Category = category;
ItemName = name;
}
public string Category { get; set; }
public string ItemName { get; set; }
public override string ToString()
{
return Category + " , " + ItemName;
}
}
}
To avoid an ongoing ping pong, if you have another question, just open a new one (if it's relevant). Otherwise, you can upvote,downvote, and mark as answered if this answered your question. :)
Well, if your first RichTextBox has each item separated by something known (e.g. NewLine), then it should be as straight forward as this:
var list = richTextBox1.Text
.Split(new[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries)
.Sort();
richTextBox2.Text = string.Join(Environment.NewLine, list.ToArray());
This will leverage the default sorting algorithm for the type. In this case string. So it will sort them alphabetically.

Categories

Resources