c# - 使用 LINQ 连接具有相同属性的字符串
问题描述
我有一个像下面这样的模型
public class PropsModel
{
public int props_id { get; set; }
public string props_name { get; set; }
public int props_order { get; set; }
}
样本值
[
{ 1, "red" ,0 }
{ 2, "green", 3}
{ 1, "light red" ,1 }
{ 3, "yellow", 2}
{ 2, "blue", 6}
]
结果字符串: “红色/浅红色”、“黄色”、“绿色/蓝色”
输出字符串规则
- 用 / 分隔具有相同 id 的字符串(例如:“red/light red”),然后用逗号分隔所有具有 Props_Order 值的组合字符串
当前实施
List<string> _inflections = new List<string>();
var distinctIDs = inflections_model.Select(x => x.form_id).Distinct(); //find distinct IDs
foreach (int _id in distinctIDs) //for each distinct ID , join the string to LIST
{
string inflection_val = string.Join(" / ", from item in inflections_model
where item.form_id==_id
select item.props_name );
_inflections.Add(inflection_val);
}
string inflection_string = string.Join(", ", _inflections); //combine processed STRINGS to a comma separate list
这会产生所需的结果,但不是按顺序(props_order 不在任何地方使用)。
我们可以对单个 LINQ 查询进行此操作吗?
解决方案
您可以尝试以下实现
var groups = list.GroupBy(x => x.props_id); //Group By Id
List<string> stringList = new List<string>(); //stringList to store common records with /
foreach(var grp in groups)
stringList.Add(string.Join("/", list.Where(x => x.props_id == grp.Key).Select(y => y.props_name))); //Logic to select property names from common groups
Console.WriteLine(string.Join(", ", stringList)); //Print result
输出:
red/light red, green/blue, Yellow
推荐阅读
- python - python fstring 格式不对齐。是字体吗?
- arrays - 如何在 laravel 刀片中显示嵌套数组数据?
- mysql - Mysql2 Gem 版本 0.3.18 到 0.4.x 不会安装在我的 Ruby on Rails 项目 Ubuntu 中
- android-studio - Android Studio 4.0 安装失败,原因是:'null'
- java - 指向 JNA 结构的指针未正确解析
- vis.js - vis-network 中的“TypeError:无法读取未定义的属性‘网络’”
- typescript - 如何键入需要返回对象副本同时还更改其属性之一的类型的函数?
- java - 如何在 Agora android 中添加文字水印?
- docker - docker build 不会复制 css 文件
- angular - 如何从 Angular 10 中的“@angular-redux/store”中进行单元测试选择?