如何修复这个linq语句?

时间:2017-08-09 18:34:21

标签: c# linq

我在C#中使用实体框架,我不确定如何继续使用此代码。我的伪代码在下面,我有一个股票交易清单,我只是试图插入数据库表中不存在的交易,但我不知道如何编写linq代码这样做。

这个当前代码给了我这个错误:

Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable<System.DateTime>' to 'Finance.Program.HistoryPrice'

public class DailyAmexData
{
    public int ID { get; set; }
    public string Symbol { get; set; }
    public DateTime Date { get; set; }
    public decimal Open { get; set; }
    public decimal High { get; set; }
    public decimal Low { get; set; }
    public decimal Close { get; set; }
    public decimal AdjustedClose { get; set; }
    public int Volume { get; set; }
}

public class HistoryPrice
{
    public DateTime Date { get; set; }
    public decimal Open { get; set; }
    public decimal High { get; set; }
    public decimal Low { get; set; }
    public decimal Close { get; set; }
    public Int32 Volume { get; set; }
    public decimal AdjClose { get; set; }
}

using (financeEntities context = new financeEntities())
{
    foreach (string symbol in symbols)
    {
        List<HistoryPrice> hList = Get(symbol, new DateTime(1900, 1, 1), DateTime.UtcNow);
        List<DailyAmexData> aList = await (context.DailyAmexDatas.Where(c => c.Symbol == symbol && hList.Contains(hList.Select(i => i.Date)) == false).ToListAsync<DailyAmexData>()); // pseudo code that I wrote so you hopefully understand what I'm trying to do here which is only return a list of DailyAmexData that doesn't exist in the database yet and then save those items to the database

      foreach(DailyAmexData item in aList)
      {
          // insert values of item in database table
      }
    }
}

更新我对我的问题进行了一些更改,以便您了解我尝试做的事情。

1 个答案:

答案 0 :(得分:1)

根据您所拥有的伪代码,我在这里看到您在评论中提到的错误:

hList.Contains(hList.Select(i => i.Date))

在那里,您要检查是否有任何HistoryPricehList.Contains)对象等于IEnumerable<DateTime>hList.Select)。

此外,您还没有在数据库中使用主LINQ查询中的DailyAmexData。将LINQ的那部分更改为以下内容:

// Before the 2nd LINQ statement
var priceDates = hList.Select(hp => hp.Date).ToList();

// Then inside your LINQ statement, replacing the piece I pointed out before.
priceDates.Contains(c.Date)