如何在 linq select 中连接列数据和 return
How to concatenate column data and return in linq select
我有一个 table,其中包含 IsAgreed、IsOther、IsEquipped 等列。在 UI 上,我显示了 3 个复选框,其中一个可以 select 单个或多个复选框。数据正按预期保存到数据库中。现在我正在尝试 select entity framework 中的数据如下
from tbl context.TableNames select new {
Conitions= tbl.IsOther ? tbl.OtherText : tbl.IsAgreed ? "Agreed :
tbl.IsEquipped? "Equipped" : "" }
当制造多个 selection 时,只给出一个 selection。我想连接并生成数据,以便它可以
OtherText, Agreed, Equipped
OtherText, Equipped
Agreed, Equipped
是否可以连接并给出预期的输出
您可以根据条件创建一个字符串数组,然后根据需要进行格式化。请注意我在代码示例中写的注释。
var conditions = context.TableNames.Select(tbl => new
{
tbl.IsOther,
tbl.IsAgreed,
tbl.IsEquipped
})
.AsEnumerable() //Should be used with caution. Because it will load each record to memory. It also switches "LINQ to Entities" to "LINQ to Objects", so we can use string.Join.
.Select(c => new
{
Conditions = string.Join(", ", new string[] { c.IsOther ? "OtherText" : "", c.IsAgreed ? "Agreed" : "", c.IsEquipped ? "Equipped" : "" }.Where(s => !string.IsNullOrEmpty(s)))
});
我有一个 table,其中包含 IsAgreed、IsOther、IsEquipped 等列。在 UI 上,我显示了 3 个复选框,其中一个可以 select 单个或多个复选框。数据正按预期保存到数据库中。现在我正在尝试 select entity framework 中的数据如下
from tbl context.TableNames select new {
Conitions= tbl.IsOther ? tbl.OtherText : tbl.IsAgreed ? "Agreed :
tbl.IsEquipped? "Equipped" : "" }
当制造多个 selection 时,只给出一个 selection。我想连接并生成数据,以便它可以
OtherText, Agreed, Equipped
OtherText, Equipped
Agreed, Equipped
是否可以连接并给出预期的输出
您可以根据条件创建一个字符串数组,然后根据需要进行格式化。请注意我在代码示例中写的注释。
var conditions = context.TableNames.Select(tbl => new
{
tbl.IsOther,
tbl.IsAgreed,
tbl.IsEquipped
})
.AsEnumerable() //Should be used with caution. Because it will load each record to memory. It also switches "LINQ to Entities" to "LINQ to Objects", so we can use string.Join.
.Select(c => new
{
Conditions = string.Join(", ", new string[] { c.IsOther ? "OtherText" : "", c.IsAgreed ? "Agreed" : "", c.IsEquipped ? "Equipped" : "" }.Where(s => !string.IsNullOrEmpty(s)))
});