Click here to Skip to main content
15,880,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I have structure with two struct objects one is string and second is int and I want to give string objects to textbox and sort them there by value of int objects. Is it possible?
Sorry of my english and possible designation mistakes.
Posted
Updated 29-Apr-12 0:21am
v2

Probably not, from your description.
A TextBox only holds Text - strings, and sorting is not one of it's features.
However, assuming your TextBox is multiline, it would be possible to put them into the TextBox in sorted order:
C#
struct MyStruct : IComparable
    {
    public string UserName;
    public int YearOfBirth;
    public MyStruct(string s, int i) { UserName = s; YearOfBirth = i; }

    public int CompareTo(object obj)
        {
        return YearOfBirth - ((MyStruct)obj).YearOfBirth;
        }
    }

    ...

    MyStruct[] arr = new MyStruct[]
       {
           new MyStruct("Joe", 1959),
           new MyStruct("Mike", 1972),
           new MyStruct("Aaron", 1999),
           new MyStruct("Jane", 1941)
       };
    Array.Sort(arr);
    List<string> lines = new List<string>();
    foreach (MyStruct ms in arr)
        {
        lines.Add(ms.UserName);
        }
    myTextBox.Lines = lines.ToArray();
 
Share this answer
 
Comments
VJ Reddy 29-Apr-12 11:48am    
Nice answer. 5!
VJ Reddy 29-Apr-12 11:58am    
I have added a solution using LINQ, by crediting your solution.
Thank you.
LosEagle 29-Apr-12 16:42pm    
Thank you guys
The Solution 1 by OriginalGriff is very good. I have added this solution only to use LINQ by using the concept and data given by OriginalGriff in his solution.
C#
void Main()
{
    MyStruct[] arr = new MyStruct[]
       {
           new MyStruct("Joe", 1959),
           new MyStruct("Mike", 1972),
           new MyStruct("Aaron", 1999),
           new MyStruct("Jane", 1941)
       };
    myTextBox.Lines = arr.OrderBy (item => item.YearOfBirth).Select (item => item.UserName).ToArray();
}
struct MyStruct
{
    public string UserName;
    public int YearOfBirth;
    public MyStruct(string s, int i) { UserName = s; YearOfBirth = i; }
}
//TextBox.Lines will be
//Jane
//Joe
//Mike
//Aaron
 
Share this answer
 
Comments
LosEagle 29-Apr-12 16:41pm    
Thank you both for your answers. Looks like both should work as I need :)
VJ Reddy 29-Apr-12 19:40pm    
You're welcome and thank you for the response.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900