英文:
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论