简体   繁体   English

是否有其他方法将列表的模型类添加到c#中的另一个模型类列表中?

[英]Any other way to add the model class of list into another model class of list in c#?

In the application I have two model class category and product. 在应用程序中我有两个模型类别和产品。 Shows below 显示如下

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CategoryId { get; set; }
}
public class Category
{
    public Category()
    {
        Products = new List<Product>();
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Product> Products { get; set; }
}

I added the data into the category and product list as below. 我将数据添加到类别和产品列表中,如下所示。

List<Category> data = new List<Category>();
data.Add(new Category { Id = 1, Name = "Plastic"});
data.Add(new Category { Id = 2, Name = "Metal"});
data.Add(new Category { Id = 3, Name = "Paper" });
foreach (var item in data)
{
    switch (item.Id)
    {
        case 1: 
            item.Products.Add(new Product { Id = 1, Name = "Doll", CategoryId = item.Id });
            item.Products.Add(new Product { Id = 2, Name = "Pen", CategoryId = item.Id });
            break;
        case 2: 
            item.Products.Add(new Product { Id = 3, Name = "Nail", CategoryId = item.Id });
            item.Products.Add(new Product { Id = 4, Name = "Key", CategoryId = item.Id });
            break;
        case 3: 
            item.Products.Add(new Product { Id = 5, Name = "Book", CategoryId = item.Id });
            break;
        default: 
            item.Products.Add(new Product { Id = 0, Name = null });
            break;
    }
}

Is there any other way to write with minimum lines of code? 有没有其他方法用最少的代码行写? I would appreciate if anyone suggest another solution for this. 如果有人建议另一个解决方案,我将不胜感激。

You can provide fluent builder methods to add products to category (it can be either extension method or instance method of category). 您可以提供流畅的构建器方法来将产品添加到类别(它可以是扩展方法或类别的实例方法)。 These methods should return category which product was added to. 这些方法应返回添加产品的类别。 And usage will look like (there are three different options to add products to category): 用法看起来像(将产品添加到类别有三种不同的选项):

var data = new List<Category> {       
   new Category { Id = 1, Name = "Plastic" } 
      .WithProducts(  
          new Product { Id = 1, Name = "Doll" }
          new Product { Id = 2, Name = "Pen" }
      ),

   new Category { Id = 3, Name = "Paper" }
      .WithProduct( new Product { Id = 2, Name = "Book" } ),

   new Category { Id = 2, Name = "Plastic" }
      .WithProduct(3, "Nail")
      .WithProduct(4, "Key"),
};

And fluent extension methods (you can use all, or pick those which syntax you like more): 和流畅的扩展方法(你可以使用所有,或选择你更喜欢的语法):

public static Category WithProduct(this Category category, int id, string product)
{
    category.Products.Add(new Product { Id = id, Name = name, CategoryId = category.Id });
    return category;
}

public static Category WithProduct(this Category category, Product product)
{
    product.CategoryId = category.Id;
    category.Products.Add(product);
    return category;
}

public static Category WithProducts(this Category category, params Product[] products)
{
    foreach(var product in products)
    {
        product.CategoryId = category.Id;
        category.Products.Add(product);
    };

    return category;
}

Note that category id will be set up automatically when you add a product to the category. 请注意,将产品添加到类别时,将自动设置类别ID。


Further notes: there is one problem with your design - when you expose category Products and id of category for modification, then it's possible that someone can add a product from another category to the products list: 附加说明:您的设计存在一个问题 - 当您公开类别Products和类别ID以进行修改时,有人可能会将其他类别的产品添加到产品列表中:

var plastic = new Category { Id = 1, Name = "Plastic"};
plastic.Products.Add(new Product {Id = 1, Name = "Doll", CategoryId = 1});
plastic.Products.Add(new Product {Id = 5, Name = "Nail", CategoryId = 2}); // plastic nail

I would at least consider disabling direct modification of category products and moved setting category id of product there: 我至少会考虑禁用类别产品的直接修改,并在那里移动产品的设置类别ID:

private List<Product> products = new List<Product>();
public IEnumerable<Product> Products => products;

public void AddProduct(Product product)
{
    // probably check if product was not added to some other category
    product.CategoryId = Id;
    products.Add(product);
}

Nothing going to be significantly shorter because it deals with object creation, so you have to make those new calls anyway. 没有什么会明显缩短因为它处理对象创建,所以无论如何你必须进行这些新的调用。 You could do something thing like... 你可以做点像......

On you Product class create a static method called Create: 在您的Product类上创建一个名为Create的静态方法:

public static Product Create(int id, string name, Category cat)
{
    return new Product { Id = id, Name = name, cat.Id };
}

then instead of writing: 然后而不是写:

item.Products.Add(new Product { Id = 1, Name = "Doll", CategoryId = item.Id });

write: 写:

item.Products.Add(Product.Create(1, "Doll", item);

I would do something similar to what Sergey Berezovskiy suggested but I would also add constructors to both classes. 我会做类似于谢尔盖别列佐夫斯基建议的东西,但我也会在两个类中添加构造函数。 Extension methods are fine but, alternatively, you could create a public method to the Category class. 扩展方法很好,但是,您也可以为Category类创建一个公共方法。

Here's the output: 这是输出:

var categories = new List<Category>
{
    new Category(1, "Plastic").WithProduct(1, "Doll").WithProduct(2, "Pen"),
    new Category(2, "Metal").WithProduct(3, "Nail").WithProduct(4, "Key"),
    new Category(3, "Paper").WithProduct(5, "Book")
};

Here's the amended Product class: 这是修改后的Product类:

public class Product
{
    public Product(int id, string name, int categoryId)
    {
        Id = id;
        Name = name;
        CategoryId = categoryId;
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public int CategoryId { get; set; }
}

Here's the amended Category class: 这是修改后的Category类:

public class Category
{
    public Category(int id, string name)
    {
        Id = id;
        Name = name;
        Products = new List<Product>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public List<Product> Products { get; set; }

    public Category WithProduct(int id, string name)
    {
        Products.Add(new Product(id, name, Id));
        return this;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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