英文:
Add object for all missing enum to the List<object>
问题
我有一个情景,其中有一个返回List<CategoriesDto>
的方法,我需要确保它包含CategoriesEnum
中提到的所有类别的列表。如果列表中缺少任何类别,我们必须添加它们。
示例代码:
Class#
public class CategoriesDto
{
public CategoriesEnum Name { get; set; }
public bool Enabled { get; set; } = false;
}
Enum#
public enum CategoriesEnum
{
TV,
AC,
Car,
Fridge
}
Case#
让我们假设以下是我们拥有的List<CategoriesDto>
:
var categoriesList = new List<CategoriesDto>
{
new()
{
Name = CategoriesEnum.TV,
Enabled = true,
},
new()
{
Name = CategoriesEnum.AC,
Enabled = true,
}
};
在这种情况下,该方法将检查枚举CategoriesEnum
中缺少的对象(在此情况下为Car, Fridge
),并将它们添加到列表categoriesList
,并将Enabled
属性的默认值设置为false
。
英文:
I Have a scenario where I have a method that returns List<CategoriesDto>
, and I need to ensure that it contains the list of all the Categories mentioned in the CategoriesEnum
. If any Categories are missing from the list, we must add them.
Sample code
Class#
public class CategoriesDto
{
public CategoriesEnum Name { get; set; }
public bool Enabled { get; set; } = false;
}
Enum#
public enum CategoriesEnum
{
TV,
AC,
Car,
Fridge
}
Case#
Let's assume that below is the List<CategoriesDto>
we have,
var categoriesList = new List<CategoriesDto>
{
new()
{
Name = CategoriesEnum.TV,
Enabled = true,
},
new()
{
Name = CategoriesEnum.AC,
Enabled = true,
}
};
In this case, the method will check the missing object from the enum CategoriesEnum
(in this case (Car, Fridge
)). It will add them to the list categoriesList
with the default value for the Enabled
property as false
.
答案1
得分: 3
你可以使用 Enum.GetValues<TEnum>
来获取枚举值,然后在其上应用 LINQ。例如:
var missing = Enum.GetValues<CategoriesEnum>()
.Except(categoriesList.Select(dto => dto.Name))
.Select(e => new CategoriesDto
{
Name = e
});
categoriesList.AddRange(missing);
英文:
You can use Enum.GetValues<TEnum>
to get enum values and then some LINQ on top. For example:
var missing = Enum.GetValues<CategoriesEnum>()
.Except(categoriesList.Select(dto => dto.Name))
.Select(e => new CategoriesDto
{
Name = e
});
categoriesList.AddRange(missing);
答案2
得分: 2
以下是翻译好的代码部分:
关键部分是 Enum.GetValues()
:
var cats = Enum.GetValues<CategoriesEnum>().
Where(e => !caterogiesList.Any(c => c.Name == e));
foreach(var cat in cats)
{
categoriesList.Add(new CategoriesDto() {Name = cat, Enabled = false});
}
英文:
The key is Enum.GetValues()
:
var cats = Enum.GetValues<CategoriesEnum>().
Where(e => !caterogiesList.Any(c => c.Name == e));
foreach(var cat in cats)
{
categoriesList.Add(new CategoriesDto() {Name = cat, Enabled = false});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论