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

时间:2013-10-29 11:32:57

标签: c# asp.net-mvc linq

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

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,name)

this.ViewData["CodeList"] = availableCodes;

2 个答案:

答案 0 :(得分:5)

您可以使用Except()

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

答案 1 :(得分:0)

假设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();
                         }