简体   繁体   English

将列表与另一个包含某些数据C#的列表同步

[英]Syncing List with another List containing Some data C#

Using winforms, Visual Studio 2013 Community, C#. 使用winforms,Visual Studio 2013社区,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: 示例:清单1包含:

[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: 清单2包含其中一些数据,但顺序不同:

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

I need some way to Get the Orders to match up so that List 2 looks like this: 我需要一些方法来使订单匹配,以使清单2看起来像这样:

[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. 通过执行上述操作,由于用户可以随时单击lista中的任何“字符串”,因此listb最终完全没有组织。 (since you can "click" lista[5],lista[1] and that there is enough to mix up the order) (因为您可以“单击” lista [5],lista [1],并且足以混合订单)

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) 我不想每次都迭代一次(Listb显示在不同的选项卡上,因此我可以在显示之前对其进行排序,但是最好以较小的块同步而不是循环遍历整个列表)

The Order I need to keep them in is the order that Lista has "strings" added to it. 我需要保留它们的顺序是Lista添加了“字符串”的顺序。 (Which I currently do by hand with Inserts). (目前,我是手工处理插入的)。

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 . 这将遍历lista ,创建所有的元素的新列表lista也发生在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. 通常,当您执行此操作时,将需要确保要比较的对象引用相等,或者已正确覆盖了这些对象的GetHashCode()Equals(Object)

In this case, since you are just using strings, you don't need to worry about this. 在这种情况下,由于您只使用字符串,因此无需担心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM