Linq查询结果改变不起作用

时间:2012-12-09 20:03:54

标签: c# .net linq

var query = from table1 in dtSzotar
            where errorList.Any(word => table1.angol.Equals(word)) ||
                  errorList.Any(word=> table1.magyar.Equals(word))
            select new QueryObject
            {
                Lesson = table1.lesson,
                English = table1.angol,
                Hungarian = table1.magyar,
                Answer = "",
            };
foreach (QueryObject row in query)
{
      String tmp;
      ((App)Application.Current).Answer.TryGetValue(row.English, out tmp); 
      row.Answer = tmp;
}

dgInCorrect.ItemsSource = query.ToList();

我也试图在数据网格中显示错误的用户答案。 tmp包含答案,但未添加到row.Answer。 此外,数据网格末尾还有一个空行。我究竟做错了什么?

这是QueryObject.cs:

class QueryObject
{
    private int lesson;
    private String english;
    private String hungarian;
    private String answer;

    public int Lesson { get { return lesson; } set { lesson = value; } }
    public String Hungarian { get { return hungarian; } set { hungarian= value; } }
    public String English{ get { return english; } set { english= value; } }
    public String Answer{ get { return answer; } set { answer= value; } }
}

1 个答案:

答案 0 :(得分:1)

你正在循环IEnumerable<QueryObject>。相反,先将查询转换为列表,然后它应该起作用:

var query = (from table1 in dtSzotar
            where errorList.Any(word => table1.angol.Equals(word)) ||
                  errorList.Any(word=> table1.magyar.Equals(word))
            select new QueryObject
            {
                Lesson = table1.lesson,
                English = table1.angol,
                Hungarian = table1.magyar,
                Answer = "",
            }).ToList();

// now query is a List<QueryObject>
foreach (QueryObject row in query)
{
      String tmp;
      ((App)Application.Current).Answer.TryGetValue(row.English, out tmp); 
      row.Answer = tmp;
}

dgInCorrect.ItemsSource = query;