Search code examples
linqilist

IList query modify one object based on another IList object - such as distinct in sql


I'm trying to write something that will distinct-ify a list, and if multiples are found set properties within the distinct list. Such as a counter on how many instances of something occurs, and maybe the last date of the occurrence. This is what I have so far.

foreach(DataObject srcObj in ilSource){
    if (ilDest.All(x => x.Property1 != srcObj.Property1 || x.srcObj != srcObj.Property2))
        ilDest.Add(srcObj);
    else
        DataObject newObject = ilDest.SingleOrDefault(x => x.Property1 == srcObj.Property1 && x.Property2 == srcObj.Property2);
        newObject.Propert3++;
        newObject.Property4 = srcObj.Property5;
}

The newObject properties are not retained, once the next iteration happens because the object is not setting back within the collection. Without Linq I would just iterate manually through the collection, grab the object and make the changes and move on to the next, because I have a true copy of the object.

Thanks in advance for any help you can contribute


Solution

  • This is my best interpretation of what you're asking.

    Try this:

    var query =
        from srcObj in ilSource
        orderby srcObj.Property5
        group srcObj by new
        {
            srcObj.Property1,
            srcObj.Property2,
        } into gs
        select new
        {
            First = gs.First(),
            Last = gs.Last(),
            Count = gs.Count(),
        };
    
    foreach (var x in query)
    {
        x.First.Property3 = x.Count;
        x.First.Property4 = x.Last.Property5;
    }
    
    var ilDest = query
        .Select(x => x.First)
        .ToList();
    

    The modification of the existing objects requires a foreach loop as LINQ is about queries and not updates.

    Nevertheless, I "fixed" your code and made my answer produce the same results. Your fixed code should look like this:

    foreach(DataObject srcObj in ilSource)
    {
        if (ilDest.All(x =>
                x.Property1 != srcObj.Property1 || x.Property2 != srcObj.Property2))
            ilDest.Add(srcObj);
        else
        {
            DataObject newObject = ilDest.SingleOrDefault(x =>
                x.Property1 == srcObj.Property1 && x.Property2 == srcObj.Property2);
            newObject.Property3++;
            newObject.Property4 = srcObj.Property5;
        }
    }