假设我有这样一个类:
class From
{
public bool FlagOne { get; set; }
public bool FlagTwo { get; set; }
public bool FlagThree { get; set; }
}
...我想将这些列表转换为这些列表:
class To
{
public List<Flag> Flags { get; set; }
}
... Flag 看起来像这样:
public enum Flag
{
One,Two,Three
}
我写了一些代码:
var froms = new List<From>
{
new From {
FlagOne = false,
FlagTwo = true,
FlagThree = true
},
new From {
FlagOne = true,
FlagTwo = false,
FlagThree = true
}
};
var tos = froms.Select(from => new To {
Flags = // ....... what? what goes here?
}).ToList();
枚举值的名称和 bool 标志并不重要。应该没有必要反射(reflection)。
上下文
我有一个这样的数据库表:
+---------+---------+-----------+
| FlagOne | FlagTwo | FlagThree |
+=========+=========+===========|
| 0 | 1 | 1 |
+---------+---------+-----------+
| 1 | 0 | 1 |
+---------+---------+-----------+
我想制作一个如下所示的 UI:
+-------------------------------------+
| Lorem blahdiblah FlagTwo, FlagThree |
+-------------------------------------+
| Lorem blahdiblah FlagOne, FlagThree |
+-------------------------------------+
我不必这样做;我只是认为这是一个有趣的问题,可以用 LINQ 解决,但找不到任何答案。
请您参考如下方法:
处理此问题的一种方法是在集合中使用可为空的 Flag,然后过滤掉 null,如下所示:
var tos = froms
.Select(f => new To {
Flags = new[] {
f.FlagOne ? (Flag?)Flag.One : null,
f.FlagTwo ? (Flag?)Flag.Two : null,
f.FlagThree ? (Flag?)Flag.Three : null
}
.Where(f => f.HasValue)
.Select(f => f.Value)
.ToList()
}).ToList();
在 Flags 赋值中创建的数组具有 Flag? 类型的三项 - 每个标志一项。对应于未设置属性的标志变为 null;与设置属性对应的标志变为可为 null 的 Flag.XYZ。
剩下的很简单:Where() 过滤掉 null,Select() 删除可空性,最后 ToList() 使结果成为一个列表。
