簡體   English   中英

匹配兩個數組之間的屬性/值數據

[英]Matching property/value data between two arrays

某個API調用返回兩個數組。 一個數組包含屬性名稱,例如

Properties[0] = "Heartbeat"
Properties[1] = "Heartbeat 2"
Properties[2] = "Some Other discovery method"

另一個數組包含Properties數組的值,例如

Values[0] = "22/01/2007"
Values[1] = "23/02/2007"
Values[2] = "5/06/2008"

值和屬性數組元素匹配,例如,值[0]始終是Properties [0]的值等。

我的目標是獲得最新的“Heartbeat *”值。 請注意,Heartbeat屬性和值並不總是在數組的元素1和2中,因此我需要搜索它們。

代碼如下所示:

static DateTime GetLatestHeartBeat(string[] Properties, string[] Values)
{
    DateTime latestDateTime = new DateTime();
    for(int i = 0; i < Properties.Length; i++)
    {
        if(Properties[i].Contains("Heart"))
        {
            DateTime currentDateTime;
            DateTime.TryParse(Values[i],out currentDateTime);
            if (currentDateTime > LatestDateTime)
                latestDateTime = currentDateTime;
        }
     }
     return latestDateTime
}

上面的代碼給了我想要的結果,只有問題是在沒有更多的Heartbeat值要查找之后循環繼續。 是否有更有效的方式來執行上述操作?

雖然這不能解決性能問題,但我會像這樣優化查詢:

var latestDateTime = Properties.Select((p, index) => 
                                     new {p, v = DateTime.Parse(Values[index])})
                                 .Where(e => e.p.Contains("Heart"))
                                 .OrderByDescending(e => e.v).First();

也許在where子句之后移動解析會限制它投射的時間。

var latestDateTime = Properties.Select((p, index) => 
                                 new {p, v = Values[index]})
                               .Where(e => e.p.Contains("Heart"))
                               .Select(e => DateTime.Parse(e.v))
                               .Max();

編輯:Per @ dbc的評論,更改.OrderByDescending(e => e).First(); Max();

我會在並行for循環中找到包含“Heart”(或其他關鍵字)的索引來加速它。 然后迭代這些索引以找到最新的索引。

    static DateTime GetLatestHeartBeat(string[] props, string[] vals)
    {
        ConcurrentBag<int> heartIndxs = new ConcurrentBag<int>();
        // find the indices of "Heart" in parallel
        Parallel.For(0, props.Length,
            index =>
            {
                if (props[index].Contains("Heart"))
                {
                    heartIndxs.Add(index);
                }
            });
        // loop over each heart index to find the latest one
        DateTime latestDateTime = new DateTime();
        foreach (int i in heartIndxs)
        {
            DateTime currentDateTime;
            if (DateTime.TryParse(vals[i], out currentDateTime) && (currentDateTime > latestDateTime))
                latestDateTime = currentDateTime;
        }

        return latestDateTime;
    }

如果使用DateTime.TryParse實際上太慢,您可以使用RegEx來解析日期字符串並進行自己的比較。 老實說,我不確定這比使用DateTime.TryParse更快。 以下是對該主題的討論: 哪個更快:DateTime.TryParse或Regex

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM