2

Using winforms, Visual Studio 2013 Community, C#.

I need to sync the order of two Lists. One of the lists contains an index, the other contains the selections out of that index.

Example: List 1 contains:

[0]Data0
[1]Data1
[2]Data2
[3]Data3
[4]Data4
[5]Data5

And List 2 Contains Some of that data But In a different Order:

[0]Data3
[1]Data1
[2]Data5

I need some way to Get the Orders to match up so that List 2 looks like this:

[0]Data1
[1]Data3
[2]Data5

Example Code:

public List<string> lista = new List<string>();
public List<string> listb = new List<string>();

public void fillListA(string mockstring)
{
    for(i=0;i<750000;i++)//just to give Idea of the number of Strings in the List
    {
        lista.add(mockstring + i.ToString());//Fill List with data
    }
}
OnClickEventHappens(string SelectedFromListA)//Mock event that fires if The user clicks on a string in ListA (As its displayed in a label on form1)
{
    if(listb.Contains(SelectedFromListA))        
    {
        listb.Remove(SelectedFromListA);
    }
    else
    {
        listb.Add(SelectedFromListA);    
    }    
}

By Doing the Above Since the user can click on Any "string" that is in lista at any point, listb ends up completely unorganized. (since you can "click" lista[5],lista[1] and that there is enough to mix up the order)

I don't want to iterate everytime It changes either (Listb is displayed on a different tab so I can sort it then before its displayed, but it would be nice to keep it synced in smaller pieces rather then looping the entire lists)

The Order I need to keep them in is the order that Lista has "strings" added to it. (Which I currently do by hand with Inserts).

1 Answer 1

1
List<string> orderedlistb = lista.Intersect(listb).ToList()

This will iterate lista, creating a new list of all of the elements in lista that also occur in listb.

In general when you do this, you will need to ensure that the objects that you are comparing are either reference equal or you have properly overridden GetHashCode() and Equals(Object) for those objects.

In this case, since you are just using strings, you don't need to worry about this.

Sign up to request clarification or add additional context in comments.

2 Comments

the lists are really just strings, Does Intersect modify lista or return a list? (eg could I do listb = lista.intersect(listb).ToList()?
@JasonBrown it returns a new List. You could indeed assign the result of that to listb if you wished.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.