C# 从两个集合创建新集合

本文关键字:集合 创建 新集合 两个 | 更新日期: 2023-09-27 18:37:21

我想从列表中删除已使用的项目以填充下拉列表

private void SetAvailableCodes(IEnumerable<ProductCodeVm> productCodes)
{
    var availableCodes = from item in Enum.GetNames(typeof(ProductCodeType))
                         where item != ProductCodeType.None.ToString()
                         select new
                         {
                             Id = (int)((ProductCodeType)Enum.Parse(typeof(ProductCodeType), item)),
                             Name = item
                         };
    // Todo remove productCodes.ProductCodeType 
    this.ViewData["CodeList"] = availableCodes;
}
public class ProductCodeVm
{
    public int Id { get; set; }        
    public int ProductId { get; set; }        
    public ProductCodeType ProductCodeType { get; set; }     <--- Enum  
    public string Value { get; set; }       
}

有没有办法使用 linq 实现这一点,或者我需要做一些强制转换或其他什么?

可用代码来自 Db

// Add codes
var codes = ProductCodeManager.GetByProductId(model.Id);
model.ProductCodes =
codes.Select(
    c =>
    new ProductCodeVm
    {
        ProductCodeType = c.ProductCodeType,
        Value = c.Value,
        ProductCodeId = c.ProductCodeId
    });
this.SetAvailableCodes(model.ProductCodes);

可用代码仅用于填充下拉列表(id,名称)

this.ViewData["CodeList"] = availableCodes;

C# 从两个集合创建新集合

您可以使用 Except()

IEnumerable<string> remainingList = allItemsList.Except(usedItemList);

假设productCodes是要过滤掉的代码列表,那么过滤而不是字符串会更容易,这样你就没有那么多解析了:

var availableCodes = 
    Enum.GetValues(typeof(ProductCodeType))
        .Except((int)ProductCodeType.None)
        .Except(productCodes.Select( p => p.Id)
        .Select(p => new {
                              Id = p;
                              Name = ((ProductCodeType)p).ToString();
                         }