我有以下物件串列:
[
{
"category": "animal",
"example": "cat"
},
{
"category": "bird",
"example": "parrot"
},
{
"category": "animal",
"example": "dog"
}
]
我需要找出重復項并輸出以下串列:
[
{
"category": "animal",
"example": ["cat", "dog"]
},
{
"category": "bird",
"example": "parrot"
}
]
使用以下代碼,我能夠找出重復項:
var a = inputList.GroupBy(x => x.category);
var duplicates = a.Where(item => item.Count() > 1);
如何更新 inputList 中示例的值?
uj5u.com熱心網友回復:
我不知道你的模型是什么樣子,但如果它看起來像這樣:
public class AnimalsWithExample
{
public AnimalsWithExample(string category, string example)
{
Category = category;
Example = example;
}
public string Category { get; set; }
public string Example { get; set; }
}
public class AnimalsGrouped
{
public string Category { get; set; }
public string[] Examples { get; set; }
}
那么你可以簡單地這樣做:
var list = new List<AnimalsWithExample>
{
new AnimalsWithExample("animal", "cat"),
new AnimalsWithExample("bird", "parrot"),
new AnimalsWithExample("animal", "dog")
};
var listGrouped = list.GroupBy(x => x.Category)
.Select(x => new AnimalsGrouped() { Category = x.Key, Examples = x.Select(y => y.Example).Distinct().ToArray() }).ToList();
uj5u.com熱心網友回復:
string和IEnumerable<string>is 的常用型別object,如果你可以接受(例如只需要 JSON),你可以使用它:
inputList.GroupBy(x => x.category).Select(grp => new
{
category = grp.Key,
examples = grp.Select(i => i.example).Distinct().ToList()
})
.Select(i => new
{
i.category,
example = i.examples.Count == 1 ? (object)i.examples.First() : i.examples
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510621.html
標籤:C#列表林克重复
