bandeee
bandeee

Reputation: 81

Ordering 2 list's elements, according to 1 list's elements

I have 2 lists, what are pairs:

List<int> timeStamp = new List<int>();
List<string> ownerStamp = new List<string>();

For example: timeStamp' elements: 1, 10, 32 ...

ownerStamp' elements: John, Dave, Maria ...

The pairs are: John-1; Dave-10; Maria-32...

I have to order the timestamp list's elements, but i have to hold the context! How can i do it? Manually? Or smthng smart with factory ordering?

Upvotes: 0

Views: 71

Answers (5)

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22794

A sorted dictionary might help.

Upvotes: 0

SergeyS
SergeyS

Reputation: 3553

There is an overload of Array.Sort() method, which allow you sort one array using other array items as keys. You can convert your lists to arrays, then sort them, and then convert back:

List<int> timeStamp = new List<int>();
List<string> ownerStamp = new List<string>();

int[] timeStampArray = timeStamp.ToArray();
string[] ownerStampArray = ownerStamp.ToArray();

Array.Sort(timeStampArray, ownerStampArray);

timeStamp = new List<int>(timeStampArray);
ownerStamp = new List<string>(ownerStampArray);

Upvotes: 2

Ohad Schneider
Ohad Schneider

Reputation: 38106

Your question doesn't specify exactly what output you're expecting, but the following will give you a sorted collection of Tuple objects, whose first item is the time-stamp and second item is the owner.

timeStamp.Zip(ownerStamp, (i,s) => Tuple.Create(i,s)).OrderBy(t => t.Item1)

Upvotes: 1

You'd probably be better off making a container object, which contains both owner and timestamp, and make it comparable:

class Entry : IComparable<Entry> {
    public int TimeStamp { get; set; }
    public string Owner { get; set; }

    public Entry(int timeStamp, string owner) {
        this.TimeStamp = timeStamp;
        this.Owner = owner;
    }

    public int CompareTo(Entry other) {
        return this.TimeStamp.CompareTo(other.TimeStamp);
    }
}

You could then make a list of these and sort it using the List<T> Sort() method.

To access the timestamp and owner, simply access the TimeStamp and Owner fields of the Entry.

Generally, if you want data to belong together, it's a good idea to explicitly group them together in an object or structure; then the grouping will happen automatically without you needing to take special care to keep things grouped.

Upvotes: 1

Chamila Chulatunga
Chamila Chulatunga

Reputation: 4914

Best if you bring the pairs together into a 'SortedDictionary', which will automatically sort the pairs for you, or create a list of tuples for the timeStamp and ownerStamp, and then sort the elements in the tuple list based on the timeStamp key.

Upvotes: 0

Related Questions