c# - 从对象子列表中删除项目 (LINQ)

标签 c# linq

我有一个看起来像这样的对象:

public class Consortium
{
    public string Id { get; set; }

    [JsonConverter(typeof(EnumDescriptionConverter))]
    public SourceType Type { get; set; }       

    public List<UserLibrary> Branches { get; set; }
}

每个 Consortium 都有一个与其关联的 UserLibrary 列表,该类如下所示:

public class UserLibrary
{
    public string LibraryId { get; set; }

    public string RetailerId {get; set;}

    public string UserId { get; set; }

    public string Name { get; set; }

    public DateTime CreatedAt { get; set; }
}

我有一种方法,允许用户从他们的联盟之一中删除库(注意:可能有许多分支与该联盟关联)。

但是,我只获得了一个 LibraryId,因此我被迫遍历他们的 Consortium 列表,找到哪个包含给定的 id,然后进行迭代越过 Twig 并删除与 id 匹配的 Twig 。

以下是我目前实现此目标的方法:

// Get the current list of consortiums
var user = _mediator.Send(new GetUserProfileCommand { UserProfileId = _principle.UserProfileId });
var userConsortia = user.SavedConsortia;

// the consortium to remove the library from
var branchToRemove = _libraryService.GetLibrary(id);
var consortRemove = new UserConsortium();

foreach (var userConsortium in userConsortia)
{    
    if (userConsortium.Branches.FirstOrDefault(c => string.Equals(c.LibraryId, id, StringComparison.OrdinalIgnoreCase)) != null)
    {
        consortRemove = userConsortium;
    }
}

// if the consortium id is null, something is f*
if (consortRemove.Id == null)
{
    return new JsonDotNetResult(HttpStatusCode.BadRequest);
}

// first remove the consortia
userConsortia.Remove(consortRemove);

// remove the branch from the consortium
consortRemove.Branches.RemoveAll(ul => string.Equals(ul.LibraryId, id, StringComparison.OrdinalIgnoreCase));

// add it back in without the branch
userConsortia.Add(consortRemove);        

问题:

这里是否缺少一个 LINQ 表达式来帮助我巩固这个逻辑,或者是否有更好的方法来做到这一点?

最佳答案

是的,您可以根据口味采取几种方法。简化现有内容的最简单方法是:

var branchToRemove = _libraryService.GetLibrary(id);
// .Single() will throw an exception unless there is one and only one match.
var consortRemove = userConsortia.Single(
    c => c.Branches.Any(
        b => string.Equals(b.LibraryId, id, StringComparison.OrdinalIgnoreCase));
// remove the consortia
userConsortia.Remove(consortRemove);

关于c# - 从对象子列表中删除项目 (LINQ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25393823/

相关文章:

c# - 如何区分usb转串口转换器?

c# - 如何在返回集合的 lambda 中使用异步

linq - EF4、Lambda、存储库模式和 DTO

c# - 使用 linq 对复杂字典求和

c# - XDocument 未正确加载

c# - webclient 通过 ssl c# xamarin 异步上传值

c# - Unity - 未检测到命名空间

c# - 在 C# 中确定操作系统和处理器类型

c# - 使用 LINQ to SQL 左连接

linq - 什么是创建独特的数据结构更好的方法:HashSet或Linq的Distinct()?