Sorting a List<Currency>

Hi,

I have a list of currencies I need to sort. How can that be done?
public class Currency
    {
        public  string lCountry{get;set;}
        public string lCurrency{get;set;}
    }

--------------------------------

        private List<Currency> getCurrency()
        {
            string textstring;
            string[] text;
            if (System.IO.File.Exists(currURI))
            {
                using (StreamReader sr = new StreamReader(currURI))
                {
                    textstring = sr.ReadToEnd();
                }
                textstring = textstring.Replace(System.Environment.NewLine, string.Empty);
                text = textstring.Split(';');
            }

            List<Currency> currlist = new List<Currency>();

            foreach (string part in text)
            {
                if (part != "")
                {
                    string[] parts = part.Split(',');
                    currlist.Add(new Currency { lCountry = parts[0].Trim(), lCurrency = parts[1].Trim() });
               }
            }

            //Sorting on lCurrency should take place here!

            return currlist;
        }

Open in new window

RTSolAsked:
Who is Participating?
 
Bob LearnedCommented:
If Currency is a custom class, then you can sort with an IComparer<Currency>.

Example:

            List<Currency> list = new List<Currency>();
            list.Sort(new CurrencyComparer());
       

        public class Currency
        {
            public string lCountry { get;set;}
            public string lCurrency { get;set;}
        }

        private class CurrencyComparer : IComparer<Currency>
        {

            public int Compare(Currency x, Currency y)
            {
                return string.Compare(x.lCurrency, y.lCurrency);
            }

        }
0
 
CCongdonCommented:
Whatever calls this method should then be able to invoke the Sort() method inherent to List<>
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
RTSolAuthor Commented:
The sort method needs some arguments since my list is a collection of Currencies. Can you help me with this?

currlist.Sort() doesn'r work.
0
 
zadeveloperCommented:
All you need to do is call the List<T>.Sort() function:

See code

private List<Currency> getCurrency()
        {
            string textstring;
            string[] text;
            if (System.IO.File.Exists(currURI))
            {
                using (StreamReader sr = new StreamReader(currURI))
                {
                    textstring = sr.ReadToEnd();
                }
                textstring = textstring.Replace(System.Environment.NewLine, string.Empty);
                text = textstring.Split(';');
            }

            List<Currency> currlist = new List<Currency>();

            foreach (string part in text)
            {
                if (part != "")
                {
                    string[] parts = part.Split(',');
                    currlist.Add(new Currency { lCountry = parts[0].Trim(), lCurrency = parts[1].Trim() });
                }
            }

            //Sorting on lCurrency should take place here!
            currlist.Sort();

            return currlist;
        }

Open in new window

0
 
zadeveloperCommented:
Sorry, Got your post after I had posted.

If .Sort() does not work then use:



currlist.Sort(new Comparison<Currency>(Currency.ToDecimal());

Open in new window

0
 
RTSolAuthor Commented:
This line throws an exeption. Is the sorting performed on lCountry or on lCurrency?

The following line produces a sorted list

var Sorted = currlist.OrderBy(p => p.lCurrency);

but this is not of the type System.Collections.Generic.List<CurrencyList> so if I use this I need to convert Sorted to System.Collections.Generic.List<CurrencyList>.

Any ideas?
0
 
Bob LearnedCommented:
Ooh, a lambda expression would mean that you can sort with LINQ...

    var Sorted = currlist.OrderBy(p => p.lCurrency).ToList();
0
 
Bob LearnedCommented:
Naughty, naughty!!  You didn't say that you were working with 3.5 and LINQ *BIG GRIN*.
0
 
RTSolAuthor Commented:
I am sorry guys - I feel a bit stupid. Please look at my code and tell me whats wrong.

currenList doesn't return anything

Help !!

btw the code below gave a buid error

        private class CurrencyComparer : IComparer<Currency>
        {

            public int Compare(Currency x, Currency y)
            {
                return string.Compare(x.lCurrency, y.lCurrency);
            }

        }

saying: Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal
Here is my call to the list method:

            List<Currency> clist = currenList();

Here is the method:

        private List<Currency> currenList()
        {
            List<Currency> currlist = new List<Currency>();
            if (System.IO.File.Exists(currURI))
            {
                using (StreamReader sr = new StreamReader(currURI))
                {
                    textstring = sr.ReadToEnd();
                }
                textstring = textstring.Replace(System.Environment.NewLine, string.Empty);
                text = textstring.Split(';');
            }
            foreach (string tt in text)
            {
                if (tt != "")
                {
                    string[] tts = tt.Split(',');
                    currlist.Add(new Currency { lCountry = tts[0].Trim(), lCurrency = tts[1].Trim() });
                }
            }
            var Sorted = currlist.OrderBy(p => p.lCurrency).ToList();
            return Sorted;
        }

and here is my Currency class:

    public class Currency
    {
        public  string lCountry{get;set;}
        public string lCurrency{get;set;}
    }

Open in new window

0
 
Bob LearnedCommented:
You have to define private classes in the right place inside the braces:

namespace TestApplication
{

      public class TestClass
      {
           
             private class MyClass
             {
             }

      }
}

I would say that if the method is not returning anything that you need to step through the code, and see if it is calling this line:

                  currlist.Add(new Currency { lCountry = tts[0].Trim(), lCurrency = tts[1].Trim() });
 
0
 
zadeveloperCommented:
Try This:

private List<Currency> currenList(string currURI)
        {
            var strings = new string[0];
            if (File.Exists(currURI))
            {
                using (var sr = new StreamReader(currURI))
                {
                    strings = sr.ReadToEnd().Replace(Environment.NewLine, string.Empty).Split(';');
                }
            }

            if (strings.Length.Equals(0)) return new List<Currency>();

            var currlist = (from tt in strings
                            where tt != ""
                            select tt.Split(',')
                            into tts select new Currency {lCountry = tts[0].Trim(), lCurrency = tts[1].Trim()}).ToList();

            return currlist.OrderBy(p => p.lCurrency).ToList();;
        }

Open in new window

0
 
zadeveloperCommented:
try this

(delete 1 of the return statments depending on which you want to use)

string[] text;

            if (!File.Exists(currURI)) return new List<Currency>();

            using (var sr = new StreamReader(currURI))
            {
                text = sr.ReadToEnd().Replace(Environment.NewLine, string.Empty).Split(';');
            }


            var currlist = new List<Currency>();

            foreach (var part in text)
            {
                if (part != "")
                {
                    var parts = part.Split(',');
                    currlist.Add(new Currency { lCountry = parts[0].Trim(), lCurrency = parts[1].Trim() });
                }
            }

            // sort by lCountry
            return new List<Currency>(currlist.OrderBy(c => c.lCountry));

            //sort by lCurrency
            return new List<Currency>(currlist.OrderBy(c => c.lCurrency));

Open in new window

0
 
zadeveloperCommented:
or using linq ...

 string[] text;

            if (!File.Exists(currURI)) return new List<Currency>();

            using (var sr = new StreamReader(currURI))
            {
                text = sr.ReadToEnd().Replace(Environment.NewLine, string.Empty).Split(';');
            }


            var currlist = (from part in text
                            where part != ""
                            select part.Split(',')
                            into parts select new Currency {lCountry = parts[0].Trim(), lCurrency = parts[1].Trim()}).ToList();

            // sort by lCountry
            return new List<Currency>(currlist.OrderBy(c => c.lCountry));

            // sort by lCurrency
            return new List<Currency>(currlist.OrderBy(c => c.lCurrency));

Open in new window

0
 
RTSolAuthor Commented:
Thanks guys - I finally got it going. I really learned a lot from thos - thanks again

-RTSol
0
 
RTSolAuthor Commented:
Hi again,

I just want to clarify a bit.

I just the line:
return new List<Currency>(currlist.OrderBy(c => c.lCurrency));
in my method. However, I also forgot to instanciate the list before the call - now it is:
        private List<CurrencyList> clist = new List<CurrencyList>();
        clist = currenList();

This was also something I didn't really had the hang of:

You have to define private classes in the right place inside the braces:

namespace TestApplication
{

      public class TestClass
      {
           
             private class MyClass
             {
             }

      }
}

Thanks again guys!
RTSol
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.