首页 > 解决方案 > 使用 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}    
]

结果字符串: “红色/浅红色”、“黄色”、“绿色/蓝色”

输出字符串规则

当前实施

    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 查询进行此操作吗?

标签: c#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

.NET 小提琴


推荐阅读