我有一个看起来像这样的对象:
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/