获取项目价格更改的最后日期

时间:2019-10-09 14:39:02

标签: c# .net class data-structures

我有3个库存,价格和已保存的列,它们来自数据库。无论价格如何变化,我们都会每天存储价格,我正试图找出价格变化的最后日期。

我尝试过的事情:

  • 使用foreach循环在inv上迭代并匹配价格,但是我迷失了方向。

  • 使用LINQ,我正在获取数据库的最后更新日期,而不是最近的价格更新日期。

  • 复制列表并将数字与打印日期不匹配的arr [0]与arr2 [1]进行比较。

代码:

namespace StackOverFlowQ2
{
    class Program
    {
        public class Data
        {
            public List<Inventory> myInv { get; set; }
        }

        public class Inventory
        {
            public string stock { get; set; }
            public string price { get; set; }
            public string saved { get; set; }
        }

        static void Main(string[] args)
        {
            var inv = new List<Inventory>
            {
                new Inventory
                {
                    stock = "Apple",  price = "31", saved = "8/10/2019 12:01:01 AM"
                },
                new Inventory
                {
                    stock = "Apple",  price = "31", saved = "8/9/2019 12:01:01 AM"
                },
                new Inventory
                {
                    stock = "Apple",  price = "31", saved = "8/8/2019 12:01:01 AM"
                },
                new Inventory
                {
                    stock = "Apple",  price = "31", saved = "8/7/2019 12:01:01 AM"
                },
                new Inventory
                {
                    stock = "Apple",  price = "28", saved = "8/6/2019 12:01:01 AM"
                },
                new Inventory
                {
                    stock = "Apple",  price = "28", saved = "8/5/2019 12:01:01 AM"
                },
                new Inventory
                {
                    stock = "Apple", price = "28", saved = "8/4/2019 12:01:01 AM"
                }
            };

            #region Solution
            //Iterate through the List
            for (int i = 0; i < inv.Count - 1; i++)
            {   
                //Compare current index to next index
                if (inv[i].price != inv[i + 1].price)
                {   
                    //Print results                                   
                    Console.WriteLine(inv[i].saved);
                    break;
                }
            }
            #endregion
        }
    }
}

当前输出:8/10/2019 12:01:01 AM

预期输出:8/7/2019 12:01:01 AM

2 个答案:

答案 0 :(得分:1)

如果saved实际上是DateTime会很好,但是我们可以在排序时进行转换。

var inStock = Model.MyInvData
    .OrderBy(x=>DateTime.ParseExact(x.saved, "dd/MM/yyyy", CultureInfo.InvariantCulture))
    .LastOrDefault();

答案 1 :(得分:1)

解决了!! :)

//Iterate through the List
for (int i = 0; i < inv.Count-1; i++)
{   
    //Compare current index to next index
    if (inv[i].price != inv[i + 1].price)
    {   
        //Print results                                   
        Console.WriteLine(inv[i].saved);
        break;
    }
}

输出:

8/7/2019 12:01:01 AM