【问题标题】:Return distinct list from a list of objects containing an array从包含数组的对象列表中返回不同的列表
【发布时间】:2021-06-20 13:15:17
【问题描述】:

我有以下对象结构:

   public class Summary{
     public string[] Sources { get; set; }
     public string Label { get; set; }
    }

我有一个查询,我在其中返回 List<Summary>

我正在尝试创建一个 linq 或 lambda 表达式,它将返回一个 List<string> 并具有不同的 Sources 值。

到目前为止我已经尝试过,但不确定它是否正确:

    var sources = Summaries.Select(x => x.Sources.Distinct().ToList());

【问题讨论】:

    标签: c# linq lambda


    【解决方案1】:

    你可以使用 GroupBy 来做到这一点。见下面的代码

    Summary a= new Summary();
    a.Label="T1";
    a.Sources=new string[]{"abc","def","xyz","abc","ccc"};
                
    var result=a.Sources.GroupBy(m=>m).Select(group=>group.First());
                
    foreach(var item in result){
        Console.WriteLine(item);    
    }
    
    

    输出将是

    abc
    def
    xyz
    ccc
    

    【讨论】:

    • 感谢您的回复!如果它在 List 中怎么办?
    猜你喜欢
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 2019-03-07
    • 2023-02-07
    • 1970-01-01
    相关资源
    最近更新 更多