移除对象列表中的重复对象,不使用任何循环语句。

huangapple go评论126阅读模式
英文:

remove the duplicate objects in list of objects without using any looping statements

问题

我正在尝试根据ID属性从对象列表中移除重复的对象。

包含重复条目的列表

[
    {
        "Id": 2,
        "Question": "skill profile",
        "Answer": "answer2"
    },
    {
        "Id": 6,
        "Question": "skill profile",
        "Answer": "skill profile"
    },
    {
        "Id": 7,
        "Question": "skill profile",
        "Answer": "answer7"
    },
    {
        "Id": 6,
        "Question": "skill profile",
        "Answer": "skill profile"
    },
    {
        "Id": 8,
        "Question": "question8",
        "Answer": "skill profile"
    }
]
list.GroupBy(x => x.Id).Select(d => d.Distinct()).ToList();

期望输出:

[
    {
        "Id": 2,
        "Question": "skill profile",
        "Answer": "answer2"
    },
    {
        "Id": 6,
        "Question": "skill profile",
        "Answer": "skill profile"
    },
    {
        "Id": 7,
        "Question": "skill profile",
        "Answer": "answer7"
    },
    {
        "Id": 8,
        "Question": "question8",
        "Answer": "skill profile"
    }
]

我尝试了使用分组的方法,但它没有起作用。请有人帮助我。

英文:

I am trying remove the duplicate objects in list of objects based on the ID prpoerty
List with Duplicate entry

[
    {
        "Id": 2,
        "Question": "skill profile",
        "Answer": "answer2"
    },
    {
        "Id": 6,
        "Question": "skill profile",
        "Answer": "skill profile"
    },
    {
        "Id": 7,
        "Question": "skill profile",
        "Answer": "answer7"
    },
    {
        "Id": 6,
        "Question": "skill profile",
        "Answer": "skill profile"
    },
    {
        "Id": 8,
        "Question": "question8",
        "Answer": "skill profile"
    }
]
list.GroupBy(x => x.Id).Select(d => d.Distinct()).ToList();

Expected Output:

[
{
    "Id": 2,
    "Question": "skill profile",
    "Answer": "answer2"
},
{
    "Id": 6,
    "Question": "skill profile",
    "Answer": "skill profile"
},
{
    "Id": 7,
    "Question": "skill profile",
    "Answer": "answer7"
},
{
    "Id": 8,
    "Question": "question8",
    "Answer": "skill profile"
}

]

I tried the group by option but it didn't worked
Please anyone help me with this

答案1

得分: 1

尝试这样做:

var result = list.GroupBy(x => x.Id).Select(x => x.First()).ToList();

如果您正在使用.NET 6或更高版本,您可以使用 DistinctBy

var result = list.DistinctBy(i => i.Id).ToList();
英文:

try this:

var result = list.GroupBy(x => x.Id).Select(x => x.First()).ToList();

If you are using .NET 6 or above, you can use DistinctBy

var result =  list.DistinctBy(i => i.Id).ToList();

huangapple
  • 本文由 发表于 2023年3月7日 16:25:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定