开发者

LINQ Outputting The Values Twice in DataGrid

        var query = from r in data.AsEnumerable()
                    select new Test
                               {
                                   Name = r.Field<string>(0),
                                   DateReported = r.Field<DateTime>(2)
                               };

        var newQuery = from i in query
                       orderby i.Name, i.DateReported
                       select i;

        myData.DataContext = newQuery;

So The problem is, I am reading an Excel Sheet and iteration over the va开发者_如何学JAVAlues. If I bind the DataContext to the DataGrid using query then everything works fine. But when i bind it to the newQuery each Item gets outputted twice

LINQ Outputting The Values Twice in DataGrid


That AsEnumerable() looks suspicious; it may have side effects that result in duplication when it is executed twice.

I admit I don't immediately see how that would happen; on the surface you would think that the select new Test{...} would force immediate evaluation, with the subsequent query working only against the results. But I have seen stranger things when someone tries to get smart with their types...

What type is data?


Try to override Equal in your Test class:

    public class Test
    {
      public string Name { get; set; }
      public DateTime DateReported { get; set; }


      public override bool Equals(object obj)
      {
        Test test = obj as Test;
        if (test == null )
          return false;

        return string.Equals(this.Name, test.Name) && this.DateReported == test.DateReported; 
      }

      public override int GetHashCode()
      {
        return Name.GetHashCode() ^ DateReported.GetHashCode();
      }
    }


Have you tried this directly?

var query = from r in data.AsEnumerable()
    orderby r.Field<string>(0), r.Field<DateTime>(2)
                    select new Test
                               {
                                   Name = r.Field<string>(0),
                                   DateReported = r.Field<DateTime>(2)
                               };

and check the result? Also it looks to me that u didn't put the actual code, u just demonstrate with a sample code. It might be from the actual code.

Waiting for your reply. Regards.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜