Home > Net >  linq distinct with object selection
linq distinct with object selection

Time:12-01

I have the following linq statement:

consumers = data.Select(x => new Consumer() 
    { 
        firstname = x.firstname, 
        lastname = x.lastname, 
        house = x.sublocationid, 
        floornr = x.floor, 
        appnr = x.roomnr 
    })
    .Distinct()
    .ToList();

Somehow this does not return distinct datasets. I assume it has something to do with the selection of the object? The distinct function is therefore not comparing the attributes directly but rather the objects? I am not understanding it fully unfortunately but in ms sql this statement works fine.

I also tried the following but it does not return a List object and I would need to use var or something else and I need a List of Consumer() objects.

consumers = data.Select(x => new Consumer() 
    { 
        firstname = x.firstname, 
        lastname = x.lastname, 
        house = x.sublocationid, 
        floornr = x.floor, 
        appnr = x.roomnr 
    })
    .GroupBy(x => new { x.firstname, x.lastname, x.haus, x.etage, x.appnr })
    .ToList();

CodePudding user response:

   You can do/try this:

        public class Consumer
        {
            public string firstname { get; set; }
            public string lastname { get; set; }
            public string floor { get; set; }
            public string house { get; set; }
        }
            List<Consumer> objConsumer = new List<Consumer>()
            {
                new Consumer(){ firstname="Govind", lastname="Sahu", house="298",floor="1st Floor"},
                new Consumer(){ firstname="Govind", lastname="Sahu", house="298",floor="1st Floor"},
                new Consumer(){ firstname="Govind1", lastname="Sahoo", house="297",floor="1st Floor"}
            };
1st approach:
        var obj = objConsumer.GroupBy(s => new {
                        s.firstname,
                        s.lastname,
                        s.house,
                        s.floor,
                    }).Select(o=>o.FirstOrDefault()).ToList();

    2nd approach:
    var obj1 = objConsumer.Select(s => new { firstname = s.firstname, lastname = s.lastname, house = s.house, floor = s.floor }).Distinct().ToList();

enter image description here

CodePudding user response:

I found another solution by using DistinctBy from MoreLinq. It returns the right result when I use it like this

consumers = data.Select(x => new Consumer() 
    { 
        firstname = x.firstname, 
        lastname = x.lastname, 
        house = x.sublocationid, 
        floor = x.floor, 
        appnr = x.roomnr 
    })
    .DistinctBy(x=> new 
    { 
        x.firstname,
        x.lastname,
        x.floor,
        x.appnr,
        x.house
    })
    .ToList();
  •  Tags:  
  • linq
  • Related