linq 具有对象选择的不同链接

eyh26e7m  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(177)

我有下面的linq语句:

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

不知何故,这并没有返回不同的数据集。我假设它与对象的选择有关?因此,不同的函数不是直接比较属性,而是比较对象?不幸的是,我并不完全理解它,但在ms sql中,这条语句工作得很好。
我还尝试了以下方法,但它没有返回List对象,我需要使用var或其他方法,我需要一个Consumer()对象的List。

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

fae0ux8s1#

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

hfsqlsce

hfsqlsce2#

我通过使用MoreLinq中的DistinctBy找到了另一个解决方案。

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

相关问题