开发者

Problem in sort by date in multi array?

开发者 https://www.devze.com 2022-12-24 03:06 出处:网络
I want to sort array A based on values in Array B actually in Array A I have topics like keyboard Laptop

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

actually in Array A I have topics like

keyboard
Laptop
Deskto开发者_开发百科p
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?


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)


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.


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));


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);
0

精彩评论

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

关注公众号