2017-01-23 3 views
0

Итак, я использую этот API, который показывает текущую цену и другие вещи, когда речь идет о монетах эфирума. И я пытаюсь создать небольшое консольное приложение, которое проверяет, изменилось ли значение с момента последнего сканирования.Как сравнить старое значение типа данных с новыми

Что я до сих пор это такое. И я знаю, что просматриваю текущее значение с текущим значением, поэтому, очевидно, его никогда не изменится. Я попытался установить переменную, которая сохранила бы старое значение, но ничего не сделала.

Как сравнить первое сканирование со вторым, чтобы увидеть, изменилось ли значение поплавка вверх или вниз?

private static void Ticker() 
     { 
      while (true) 
      { 
       const string uri = @"https://api.coinmarketcap.com/v1/ticker/ethereum/"; 
       var client = new WebClient(); 
       var content = client.DownloadString(uri); 

       var results = JsonConvert.DeserializeObject<List<CoinApi>>(content); 

       float currentAmount = results[0].price_usd; 
       if (currentAmount < currentAmount) 
       { 
        Console.WriteLine("Ammount is lower than the last time."); 
       } 
       else if (currentAmount > currentAmount) 
       { 
        Console.WriteLine("The amount is higher than the last time."); 
       } 
       else if (currentAmount == currentAmount) 
       { 
        Console.WriteLine("The amount hasnt changed since the last time we scanned."); 
       } 
      } 
     } 

И это файл класса.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace CryptoTicker.Core 
{ 
    class Main 
    { 
    } 

    public class CoinApi 
    { 
     public string Id { get; set; } 
     public string Name { get; set; } 
     public string Symbol { get; set; } 
     public float price_usd { get; set; } 
    } 
} 

ответ

0

Вам нужно будет запомнить предыдущее значение. Один из способов сделать это может быть, чтобы сохранить словарь из идентификаторов и CoinApi классы

public Dictionary<int, CoinApi> CoinDict = new Dictionary<int, CoinAPI>(); 

Затем вы можете сохранить текущие значения в этом словаре, а затем сравнить новые значения, против этого существующих значений. А затем обновить до новых значений

public void UpdateCoinDict(CoinApi coin) 
{ 
    CoinDict[coin.Id] = coin; 
} 

public float GetCoinPrice(CoinApi coin) 
{ 
    if (CoinDict.Contains(coin.Id)) 
    { 
     return CoinDict[coin.Id].price_usd; 
    } 
    else 
    { 
     UpdateCoinDict(coin); 
     return coin.price_usd; 
    }    
} 



private static void Ticker() 
{ 
    while (true) 
    { 
     const string uri = @"https://api.coinmarketcap.com/v1/ticker/ethereum/"; 
     var client = new WebClient(); 
     var content = client.DownloadString(uri); 

     var results = JsonConvert.DeserializeObject<List<CoinApi>>(content); 

     for (coin in results) 
     { 
      float currentAmount = coin.price_usd; 
      float oldPrice = GetCoinPrice(coin); 
      if (currentAmount < oldPrice) 
      { 
       Console.WriteLine("Ammount is lower than the last time."); 
      } 
      else if (currentAmount > oldPrice) 
      { 
       Console.WriteLine("The amount is higher than the last time."); 
      } 
      else 
      { 
      Console.WriteLine("The amount hasnt changed since the last time we scanned."); 
      } 
     } 
    } 
} 
+0

Мой подход позволяет обрабатывать несколько экземпляров монеты, если вам нужно только управлять одной ценой, тогда другие пользователи размещают более простые подходы, которые могут быть более желательными – Ben

0

Попробуйте сохранить старое значение в статической переменной, чтобы исправить вашу проблему. ТОДОС: Что ты собираешься сделать с первой просьбой? Исключения для ручек и т. Д.

Другие вопросы: Должен ли он работать в while(true)? Возможно, вы должны использовать HttpClient и повторно использовать его.

private static float _oldValue; 

    private static void Ticker() 
    { 
     while (true) 
     { 
      const string uri = @"https://api.coinmarketcap.com/v1/ticker/ethereum/"; 
      var client = new WebClient(); 
      var content = client.DownloadString(uri); 

      var results = JsonConvert.DeserializeObject<List<CoinApi>>(content); 

      float currentAmount = results[0].price_usd; 
      if (currentAmount < _oldValue) 
      { 
       Console.WriteLine("Ammount is lower than the last time."); 
      } 
      else if (currentAmount > _oldValue) 
      { 
       Console.WriteLine("The amount is higher than the last time."); 
      } 
      else if (currentAmount == _oldValue) 
      { 
       Console.WriteLine("The amount hasnt changed since the last time we scanned."); 
      } 

      _oldValue = currentAmount; 
     } 
    } 
0

Как вы его написали, currentAmount всегда будет равен самому себе.

Это должно работать:

private static void Ticker() 
{ 
    float previousAmount = 0.0; 
    while (true) 
    { 
     const string uri = @"https://api.coinmarketcap.com/v1/ticker/ethereum/"; 
     var client = new WebClient(); 
     var content = client.DownloadString(uri); 

     var results = JsonConvert.DeserializeObject<List<CoinApi>>(content); 

     float currentAmount = results[0].price_usd; 

     if (currentAmount < previousAmount) 
     { 
      Console.WriteLine("Ammount is lower than the last time."); 
     } 
     else if (currentAmount > previousAmount) 
     { 
      Console.WriteLine("The amount is higher than the last time."); 
     } 
     else if (currentAmount == previousAmount) 
     { 
      Console.WriteLine("The amount hasnt changed since the last time we scanned."); 
     } 
     previousAmount = currentAmount; 
    } 
} 
0

Вы должны пройти предыдущее значение выполнения для текущего выполнения сравнения. Объявите эту переменную как в глобальной оценке внутри этого класса. Или объявите его на уровне, где вы хотите его использовать.