开发者

Problem with sorting list

开发者 https://www.devze.com 2023-01-21 00:28 出处:网络
I have a problem with sorting collection. User saves few valuesand he sorts it. At next launchprogram must order a new collection.

I have a problem with sorting collection. User saves few values and he sorts it.

At next launch program must order a new collection.

Values which have been saved by user can be in new collection, but It can be situation , when those values aren't in new collection.

I wrote some code, and I want your feedback If it has sense

var oldValues = new List<string>(new[] { "id5", "id3", "id1" });
var valuesToOrder = new List<string>(new[] { "id1", "id2", "id3", "id4" });

int numberOfReorderedValues = 0;

for (int i = 0; i < oldValues.Count; i++)
{
    if (valuesToOrder.Contains(oldValues[i]))
    {
         int indexOfValueWhichShouldBeBefore = valuesToOrder.IndexOf(oldValues[i]);
         string valueWhichShouldBeBefore = valuesToOrder[indexOfValueWhichShouldBeBefore];

         string valueWhichShouldBeAfter = valuesToOrder[numberOfReorderedValues];

         valuesToOrder[numberOfReo开发者_如何学PythonrderedValues] = valueWhichShouldBeBefore;
         valuesToOrder[indexOfValueWhichShouldBeBefore] = valueWhichShouldBeAfter;


         numberOfReorderedValues++;

This code works, but I must tomorrow show it to my boss, and I don't go to fool


It's not clear what you're after.

It sounds like you've got 2 lists. One of them contains a list of 'required', and the other contains a list of 'pick from'.

How about use LINQ to sort?

var oldValues = new List<string>(new[] { "id5", "id3", "id1" });
var valuesToOrder = new List<string>(new[] { "id1", "id2", "id3", "id4" });

var sorted = valuesToOrder.Intersect(oldValues).OrderBy(x=>x);

// sorted now has id1 and id3, sorted alphabetically.
0

精彩评论

暂无评论...
验证码 换一张
取 消