Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by David_29 · Jul 31, 2015 at 06:53 AM · buglistsortgameobject.namenumerical

Sorting Game Object Name In Numerical and Alphabetical Order via List

I need help on this one. I took some research about sorting GameObject in alphabetical and numeric order. I implemented this code like this:

             if(SortCardOrder) {

                 List<GameObject> cardOrder = null;
                 cardOrder = this.card[0].OrderBy(go=>go.name).ToList(); // --> I use this code to sort by name.

                 foreach(GameObject card in cardOrder) {
                     
                     CardPosition[] position = card.GetComponents<CardPosition>();

                     // Display result here.
                     print ("[ CARD IN HAND ] --> " + position[0].getSuit() + " " + position[0].getCardNumber() + 
                            " at player " + 1 + ".");
                     cardText.text += "" + position[0].getSuit() + " " + position[0].getCardNumber() + 
                         " at player " + 1 + ". \n";
                     
                 }

             }

When I check it via console or via GUI Text preview and I found that it was sorted not completely alphabetical and numerical but lexicographical. (See example below.)

 /**
  * 
  * EXPECTED, RESULT IN OUTPUT: (Correct)
  * Club 1
  * Club 2
  * Club 10
  * Diamond 5
  * Diamond 6
  * Heart 10
  * Spade 1
  * Spade 2
  * Spade 10
  * 
  * REALITY, RESULT IN OUTPUT: (Wrong)
  * Club 1
  * Club 10
  * Club 2
  * Diamond 5
  * Diamond 6
  * Heart 10
  * Spade 1
  * Spade 10
  * Spade 2
  *
  * (Sometimes, it display the result by sorting the one with numbers in lexical order
  *  first before the letters.)
  *
  * Ex. "Hearts 1, Clubs 3, Spade 3, Diamonds 4, Diamonds 5"
  * 
  */

I found this source useful and the only way to sort game object by name is to sort alphabetically and numerically in order to met the result for my card game so that I can use it to compute for the end game results. Currently, I still looking for this answer for this problem about this sorting problem. A contribution for help or tip will be appreciated.

UPDATE (As of 8/6/2015): After I observed their answers about IComparer syntaxes, I check on this link and I made this solution (with Comparison<GameObject> as the parameter of the Sort() method) like this:

     cardOrder = this.card[playerIndex];
     cardOrder.Sort((s1, s2)=>{

         string pattern = "([A-Za-z])([0-9]+)";
         string h1 = Regex.Match(s1.name, pattern).Groups[1].Value;
         string h2 = Regex.Match(s2.name, pattern).Groups[1].Value;
         if (h1 != h2) return h1.CompareTo(h2);
         string t1 = Regex.Match(s1.name, pattern).Groups[2].Value;
         string t2 = Regex.Match(s2.name, pattern).Groups[2].Value;
         return int.Parse(t1).CompareTo(int.Parse(t2));

     });

Unfortunately, I still got errors yet. This error message shown in the console like this:

 FormatException: Input string was not in the correct format
 System.Int32.Parse (System.String s) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Int32.cs:629)
 CardInHand.<ResortAndRegroupCard>m__0 (UnityEngine.GameObject s1, UnityEngine.GameObject s2) (at Assets/Bet Module/CardInHand.cs:594)
 System.Array.qsort[GameObject] (UnityEngine.GameObject[] array, Int32 low0, Int32 high0, System.Comparison`1 comparison) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Array.cs:1772)

And, in order to re-arrange string value from a GameObject name (since I created a List object for storing a lot of GameObjects) is to find out how to sort a List of GameObjects by fetching its name as string value and compare it in order to arrange in alpha-numeric order.

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image David_29 · Jul 31, 2015 at 06:56 AM 0
Share

That's a good one. But though, I still want to know how to arrange them in alpha-numerical order.

avatar image David_29 · Aug 06, 2015 at 02:54 AM 0
Share

I added additional info updated. (See section: UPDATE (As of 8/6/2015))

2 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by NeverHopeless · Jul 31, 2015 at 08:26 AM

There is no direct procedure to achieve this you need custom ordering. As a quick guideline, i came up with a simple sample:

 List<string> ls = new List<string> (new string[] {"Club 1","Club 10","Club 2","Diamond 5","Diamond 6","Heart 10","Spade 1","Spade 10","Spade 2"});

 for(int i = 0; i <ls.Count;i++) {
 Match m = Regex.Match (ls[i], "(\\d+)");
 string num = m.ToString().PadLeft(5, '0');
 ls[i] = ls[i].Replace(m.ToString(), num);
     print(ls[i]);
 }

 // order based on padded results
 var data = ls.OrderBy((c) => c);
 for(int i = 0; i < data.Count(); i++) {
     print (Regex.Replace(data.ElementAt(i), "([0]+)([1-9]+)", "$2"));
 }


You can also find dozens of examples to achieve this. Following are the recommended reads:

Alphanumeric sorting using LINQ

How to sort number in alphanumeric

EDIT:

Based on your comment i am adding a bit of explanation, see if it helps to fix your current code.

My first for loop prefix the number with zeros, so the numbers have equal length:

Club 00001 Club 00010 Club 00002

At this point the comparer's default behavior evaluates that it should appear in this sequence:

Club 00001 Club 00002 Club 00010

This is our desired result, but without leading zeros, so my second for loop fixes it and makes:

Club 1 Club 2 Club 10

which is the desired result.

Comment
Add comment · Show 10 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image NeverHopeless · Aug 06, 2015 at 07:33 AM 0
Share

@$$anonymous$$_29, didn't you tried the one i suggested? ls in my case is this.card[0] in your case.

avatar image David_29 · Aug 06, 2015 at 08:31 AM 0
Share

@NeverHopeless I tried yours...as my reference. I took the two links you've gave me to further gain more ideas about how to compare two objects in order to sort GameObject in alpha-numerical. Attempting to re-arrange all GameObjects in a List by sorting through getting the the string value of each GameObject's name and setup the parameter for method in what kind of way of arranging in order within Sort() method or OrderBy() method of the List object. I haven't fully understand yet.

avatar image David_29 · Aug 06, 2015 at 08:37 AM 0
Share

@NeverHopeless ...Where this.card[0] is the object name of List<GameObject>.

avatar image NeverHopeless · Aug 06, 2015 at 08:41 AM 0
Share

Ok what did you get when you used my code in place of your's Sort(s1, s2) ?

avatar image David_29 · Aug 06, 2015 at 08:46 AM 0
Share

@NeverHopeless The middle one. Tried but no luck yet. Just straight and see if it works before re-modifying the code for arranging GameObject in alpha-numeric.

Show more comments
avatar image
1

Answer by GiyomuGames · Jul 31, 2015 at 07:18 AM

I found this which may solve your problem: http://www.dotnetperls.com/alphanumeric-sorting

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

6 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

A node in a childnode? 1 Answer

How to sort a list of gameobjects by their name? 4 Answers

Sort List by another List Values - Different Type 1 Answer

Sort list with non-anonymous delegate? 2 Answers

merge sort crash Unity 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges