Snekri Pyrope
Snekri Pyrope

Reputation: 1

How do you find the date that you want from one of Dictionary values?

As the title suggests, How do you find date that you want from one of the dictionary values which is date time?

I tried many time in an attempt to find such date but it said that date is not found even it is in one of the values!

What to do?

public static void ListAllSalesByDate()
{
   int orderCount = 0;
   double totalCount = 0;

   DateTime input;

   int id = 0;

   Console.Write("Enter the date: ");
   if (DateTime.TryParse(Console.ReadLine(), out input))
   {
      foreach (KeyValuePair<int, Sale> sale in sales)
      {
         if (sale.Value.Today == input)
         {
            id = sale.Key;

         }
      }
      if (sales.ContainsKey(id))
      {

         for (int i = 0; i <= sales.Count; i++)
         {
            orderCount++;

            Console.WriteLine("\nOrder(s) Found for {0}!\n", input.ToString("MM/dd/yyyy"));

            Console.WriteLine("Order ID:  Total:");
            Console.WriteLine("=========  =======");
            Console.WriteLine($"{sales[id].OrderID:D5}  {sales[id].Finaltotal:C}");

            totalCount += sales[i].Finaltotal;

            Console.WriteLine($"{orderCount} order(s) found for a total of {totalCount:C} on {sales[id].Today}");
         }
      }
      else
      {
         Console.WriteLine($"\nthe date of {input.ToString("MM/dd/yyyy")} was not found. Try again.\n");
      }
   }
   else
   {
      Console.WriteLine($"\nthe date of {input.ToString("MM/dd/yyyy")} was not found. Try again.\n");
   }
}

Upvotes: 0

Views: 273

Answers (1)

TheGeneral
TheGeneral

Reputation: 81493

Assuming you want to compare just the Date Component of a DateTime and want the KeyValuePair, just use FirstOrDefault

Returns the first element of the sequence that satisfies a condition or a default value if no such element is found.

var result = sales.FirstOrDefault(x => x.Value.Date == input.Date);

if(result != null)
{
   // you have found the dictionary entry
   var id = result.Key;
   ...
}
else
{
   // not found
}

If there can be more than one Date that matches, you can use Where

Filters a sequence of values based on a predicate.

var results = sales.Where(x => x.Value.Date == input.Date).ToList();

if(!results.Any())
{
   foreach(var entry in results)
   {
       var id = result.Key;
      ...
   }
}
else
{
   // not found
}  

Upvotes: 1

Related Questions