lexeme
lexeme

Reputation: 2973

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.AbcDataGrid.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:enter image description here

Upvotes: 1

Views: 219

Answers (1)

Edgar Hernandez
Edgar Hernandez

Reputation: 4030

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()
                };

Upvotes: 5

Related Questions