[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Sorting a List<Currency>

Posted on 2010-01-08
16
Medium Priority
?
373 Views
Last Modified: 2012-05-08
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

0
Comment
Question by:RTSol
  • 5
  • 5
  • 4
  • +1
16 Comments
 
LVL 9

Expert Comment

by:CCongdon
ID: 26213976
Whatever calls this method should then be able to invoke the Sort() method inherent to List<>
0
 
LVL 9

Expert Comment

by:CCongdon
ID: 26213985
0
 

Author Comment

by:RTSol
ID: 26214106
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 13

Expert Comment

by:zadeveloper
ID: 26214142
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
 
LVL 13

Expert Comment

by:zadeveloper
ID: 26214227
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
 
LVL 96

Accepted Solution

by:
Bob Learned earned 1000 total points
ID: 26214232
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
 

Author Comment

by:RTSol
ID: 26214257
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
 
LVL 96

Expert Comment

by:Bob Learned
ID: 26214300
Ooh, a lambda expression would mean that you can sort with LINQ...

    var Sorted = currlist.OrderBy(p => p.lCurrency).ToList();
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 26214305
Naughty, naughty!!  You didn't say that you were working with 3.5 and LINQ *BIG GRIN*.
0
 

Author Comment

by:RTSol
ID: 26214534
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
 
LVL 96

Expert Comment

by:Bob Learned
ID: 26214692
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
 
LVL 13

Expert Comment

by:zadeveloper
ID: 26214761
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
 
LVL 13

Expert Comment

by:zadeveloper
ID: 26234046
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
 
LVL 13

Assisted Solution

by:zadeveloper
zadeveloper earned 1000 total points
ID: 26234146
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
 

Author Closing Comment

by:RTSol
ID: 31674774
Thanks guys - I finally got it going. I really learned a lot from thos - thanks again

-RTSol
0
 

Author Comment

by:RTSol
ID: 26270480
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Loops Section Overview
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses
Course of the Month18 days, 9 hours left to enroll

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question