提问者:小点点

如何使用Linq获取唯一对象


嗨可以有人协助请,我有一个列表,其中包含我的推广代码和在列表中我想返回只出现一次即没有重复的推广代码,请看下面的数据从JSON,我想返回推广代码A123和B500,并将它们存储在另一个列表。

[
   {
    "PromCode": "A123",
    "Priority": 1,
    "offer": "Win a Free Cap",
    "StartDte": "2020-08-11T00:16:23.184Z",
    "endDte": "2020-09-10T17:16:23.184Z",
  }, 
  {
    "PromCode": "A100",
    "Priority": 1,
    "offer": "Win a perfume",
    "StartDte": "2020-08-11T00:16:23.184Z",
    "endDte": "2020-09-10T17:16:23.184Z",
  },
{
    "PromCode": "A100",
    "Priority": 2,
    "offer": "Win a Phone pouch",
    "StartDte": "2020-09-11T00:16:23.184Z",
    "endDte": "2020-10-10T17:16:23.184Z",
  },
 {
    "PromCode": "B500",
    "Priority": 1,
    "offer": "Win a free router",
    "StartDte": "2020-08-11T00:16:23.184Z",
    "endDte": "2020-09-10T17:16:23.184Z",
  },
 {
    "PromCode": "H300",
    "Priority": 2,
    "offer": "Win a free router",
    "StartDte": "2020-08-11T00:16:23.184Z",
    "endDte": "2020-09-10T17:16:23.184Z",
  },

]

我有一个包含所有这些升级代码的列表,如下所示,注意:并且我已经成功地序列化了JSON对象

var existingProms = await _Repo.GetAllPromCodes(promCodeList);

我试着在列表中出现过一次,就像这样

  var distinctList = existingProms.GroupBy(x => x.PromCode).Where(y => y.Count() == 1)
                   .Select(x => x.Key.ToString()).ToList();

请注意,上面的返回distinct PROM(B500,A123,H300),但是只返回PromCode,而不是该对象中的所有其他字段。我想返回一个所有对象的列表,其中distinct和not,并且优先级为1.这意味着distinct列表的最终结果必须包含两个对象,如下所示。

distinctList = {
    "PromCode": "A123",
    "Priority": 1,
    "offer": "Win a Free Cap",
    "StartDte": "2020-08-11T00:16:23.184Z",
    "endDte": "2020-09-10T17:16:23.184Z",
  }, 
 {
    "PromCode": "B500",
    "Priority": 1,
    "offer": "Win a free coffee mug",
    "StartDte": "2020-08-11T00:16:23.184Z",
    "endDte": "2020-09-10T17:16:23.184Z",
  },


共2个答案

匿名用户

在groupby中,您需要选择分组的第一个元素,而不是选择:

var distinctList = existingProms
    .GroupBy(x => x.PromCode)
    .Where(y => y.Count() == 1)
    .Select(x => x.First()) // Changed from .Select(x => x.Key.ToString())
    .ToList();

匿名用户

只需对原始查询进行额外修改,就可以达到此目的:

        var distinctList = existingProms
            .GroupBy(x => x.PromCode)
            .Where(y => y.Count() == 1 && y.First().Priority == 1)
            .Select(x => x.First())
            .ToList();

由于y.count()==1确保在组中只获得一个项目,因此可以使用first获取该项目,并在中按其筛选priority。其中(y=>y.count()==1&y.first().priority==1)并在下一个方法调用中选择该对象。

上面是方法语法示例,在表达式语法中为:

    var distinctList = (from ep in existingProms
                        group ep by ep.PromCode into g
                        where g.Count() == 1 && g.First().Priority == 1
                        select g.First())
                        .ToList();