1

I want to sort array A based on values in Array B

actually in Array A I have topics like

keyboard
Laptop
Desktop
mouse

and in Array B i have dates associated with each value in Array A how i can achieve this....I was thinking of using multi array but i m not sure if there is any default method of sorting multi array ...or if there is any other method to achieve this?

4 Answers 4

3

Use:

Array.Sort (A, B, comparer); // comparer can be null here to use the default

where A is the DateTime [] and B is the string [] with A[0] being the date that corresponds to the string B[0] and so on. (MSDN docs here)

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

2 Comments

thanks Gonzalo for your reply...so my final array would be array B sorted based on array A rite ? and comparer function, can i use the same comparer defined in the msdn doc...?
Whenever a key in array A is moved, the corresponding value in B will be moved to the same index position. For DateTime you can use 'null' as the comparer.
0

Create an object with two properties: a string for your topic and a datetime for your dates. Place those objects in an array or collection and you can then sort on the date and choose to project an array of your topics if you so desire.

Comments

0

If you are managing this completely, you might want to put these into a single class:

class HardwareElement
{
    public HardwareElement(string topic, DateTime date)
    {
       this.Topic = topic;
       this.Date = date;
    }
    public string Topic { get; set; }
    public DateTime Date { get; set; }
}

Then, given an array of the above, you can sort these easily:

HardwareElement[] theArray = PopulateMyArray();

Array.Sort(theArray, (l, r) => l.Date.CompareTo(r.Date));

Comments

0

Unless you have a specific reason, you probably shouldn't be storing two associated pieces of data in completely separate arrays.

you could possibly try something like the following:

public enum Device
{
    Laptop,
    Mouse,
    Keyboard 
}

public struct DeviceEvent
{
    public DeviceEvent(Device device, DateTime timestamp) : this()
    {
        Device = device;
        TimeStamp = timestamp;
    }
    public Device Device { get; set; }
    public DateTime TimeStamp { get; set; }
}


List<DeviceEvent> deviceEvents = new List<DeviceEvent>();
deviceEvents.Add(new DeviceEvent(Device.Keyboard, DateTime.Now);
deviceEvents.Add(new DeviceEvent(Device.Mouse, DateTime.Today);
... etc

IEnumerable<DeviceEvent> orderedDeviceEvents = deviceEvents.OrderBy(e = > e.TimeStamp);

Comments

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.