简体   繁体   中英

How to get a distinct list from child list inside parent list LINQ c#

I have an object called CheckItem have inside it List SubItems how can i distinct this SubItems by id of subItems using LINQ in C#

I find the solution

        var re21r = final.Select
                 (
                         c => new CheckItem
                         {
                             Id = c.Id,
                             Name = c.Name,
                             SubItems = c.SubItems.GroupBy(d=>d.Id).Select(f=>f.FirstOrDefault()).ToList()//.Distinct().ToList()//.Select(room => new CheckItem { Id = room.Id, Name = room.Name }).GroupBy(item => item.Id)
                                            //  .Select(group => group.FirstOrDefault())
                         }).ToList();

public class CheckItem
{
    /// <summary>
    /// Gets or sets the id.
    /// </summary>
    public Guid Id { get; set; }

    /// <summary>
    /// Gets or sets the name.
    /// </summary>
    public string Name { get; set; }


    /// <summary>
    /// Gets or sets the sub items.
    /// </summary>
    public List<CheckItem> SubItems { get; set; }

}

Updated based on your comment:

public class CheckItem
{
    public CheckItem()
    {
        _privateList = new List<CheckItem>();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
  
    //made list private
    private List<CheckItem> _privateList{ get; set; }

    //added public readonly list
    public ReadOnlyCollection<CheckItem> ReadSubItems 
    {
        get 
        {
             return _privateList.AsReadOnly();
        }
    }


    /// Added "Add" function
    public void AddSubItem(CheckItem target)
    {
        if (!_privateList.Any(c => c.Id == target.Id)
            _privateList.Add(target);

    }
}

Original answer:

It would be something like this:

var checkItem = /* get it somehow */;
var distinctIdList = checkItem.SubItems.Select(c => c.Id).Distinct();

I'll dig up an example on how to get the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM