0

I have a list of objects and I want to check if there is objects with the same property values:

Level is an object, that means levels of a house and has a property called elevation.

listOflevels is a list of my object Level

I would like to know if in my list(listOflevels) there is two or more levels with the same elevation.

Ex.: If I have one level with level.elevation = 3 and another one with level.elevation = 3, then the method should return true

I tried this way, but I wonder if there is a better way

foreach (Level level in listOflevels)
    {
        double levelElevation = level.Elevation;
        foreach (Level level2 in listOflevels)
        {
            if ((level2.Name != level.Name && level2.Elevation == levelElevation)
            {
                return true;
            }
        }
    }

Can LINQ be used to improve this?

Many Thanks

  • Linq can improve the readability, but not performance. Look for `GroupBy` for example. The code you show is broken and will always return `true` if there is at least one element in `listOFLevels`. You'd need to check that `level2 != level` to find duplicates. – René Vogt Nov 11 '21 at 12:08
  • https://stackoverflow.com/questions/18547354/c-sharp-linq-find-duplicates-in-list – user3953989 Nov 11 '21 at 12:09
  • after looking at your code, if It put in my words are you just trying to find whether the list that you are processing contains more than one of the value that is being compared? – Abhinav Pandey Nov 11 '21 at 12:13
  • `return listOflevels.GroupBy(l => l.Elevation).Any(c => c.Count() > 1);` this will do the equivalent using linq – Ibram Reda Nov 11 '21 at 12:18
  • @RenéVogt i just updated the code – Rodrigo Matos Nov 11 '21 at 12:20
  • @IbramReda though the result is correct, this is slower than the original code. Depending on what critieria OP is trying to "improve" (speed/memory/readability) this may be the correct or wrong answer. – René Vogt Nov 11 '21 at 12:28
  • @AbhinavPandey Yes! – Rodrigo Matos Nov 11 '21 at 12:47
  • @IbramReda this worked perfectaly! i was trying improve readability. – Rodrigo Matos Nov 11 '21 at 12:50
  • @RenéVogt yes, you are completely right. I did not say it is faster or answer the question, i just mention linq implementation because I thought the author search for it not for faster code because he did not mention any speed/ size issue – Ibram Reda Nov 11 '21 at 12:51
  • @RodrigoMatos Your update should be equivalent to this `return listOflevels.DistinctBy(l=>l.Name).GroupBy(l => l.Elevation).Any(c => c.Count() > 1);` – Ibram Reda Nov 11 '21 at 12:52

0 Answers0