开发者

Data duplication in DataGrid. Problem with LINQ query

I have such a query but it gives me wrong output. I have two data collections abcdata && xyzdata. each collection consists of an anonymous objects that have Group, Name properties. What I need to do is to get resulting collection with merged groups from abcdata and xyzdata respectively.

if(this.AbcDataGrid.ItemsSource != null && this.XyzDataGrid.ItemsSource != null)
{
       var abcdata = ((IEnumerable<dynamic>)this.AbcData开发者_Python百科Grid.ItemsSource).ToList().OrderByDescending(x => x.Id);
       var xyzdata = ((IEnumerable<dynamic>)this.XyzDataGrid.ItemsSource).ToList().OrderByDescending(x => x.Id);

       var result = from i1 in abcdata
                    from i2 in xyzdata
                    select new
                    {
                        Name  = i1.Name,
                        Group = i1.Group.ToString() + i2.Group.ToString()
                    };

        this.ResultGrid.ItemsSource = result.ToList();
    }

While I was expecting to get DataGrid populated with list of new {Name, Group} objects I have very strange result:

Data duplication in DataGrid. Problem with LINQ query


I believe that what you are trying to do is join both data collections. The linq query that you are doing is returning the correct results as what you are asking with it is: for every element of abcdata, and for every element of xyzdata, return the object you are constructing. So, if abcdata has 3 elements and xyzdata has 5 elements, the result will have 15 elements.

If you want: for each element of abcdata, select the elements of xyzdata that have the same name and concatenate the Groups, what you need is a Join.

Something like

var result = from i1 in abcdata
                join i2 in xyzdata on i1.Name equals i2.Name
                select new
                {
                    Name  = i1.Name,
                    Group = i1.Group.ToString() + i2.Group.ToString()
                };
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜