C# 如何向 List<string> 添加一个元素?

C# How to add an element to List<string>?

如何将电影元素添加到现有类别元素中?目前我只能在两个字段上创建新的列表条目。

class MovieSolver
    {
        public string Category { get; set; }
        public List<string> Movie { get; set; }
    }
class CreateMovieList
    {
        readonly static List<MovieSolver> playerTargetList = new List<MovieSolver>();

        public static void MovieCBO()
        {
            playerTargetList.Add(new MovieSolver { Category = "Action", Movie = new List<string> { "Taken", "The Factory", "Wind River" } });
            playerTargetList.Add(new MovieSolver { Category = "Comedy", Movie = new List<string> { "Gold", "Hangover", "We are the Millers" } });
            playerTargetList.Add(new MovieSolver { Category = "Thriller", Movie = new List<string> { "Jack Reacher", "Real Steel", "Iron Man I" } });
        }
    }

此外还有更聪明的方法来创建class MovieSolver吗?

首先,我在这里根本找不到int列表。

如果您想将新的字符串对象添加到 MoveiSolver 对象中的列表中,您首先需要找到要添加新字符串元素的 Moviesolver 对象。

您可以使用 for 循环、foreach 循环或 LINQ 执行此操作。

foreach 对于新编码人员来说通常是最容易理解的。

Foreach item in playerTargetList
{
 if(item.category == "Action")
 {
  item.Movie.add("lorum ipsum");
 }
}

为什么不使用默认值 class,例如 Dictionary<string, List<string>>

//Add library reference
using System.Collections.Generic;

public void MyMethod()
{
    //Initialize a Dictionary
    Dictionary<string, List<string>> MovieCBO = new Dictionary<string, List<string>>();
    //Check if its an existing category
    //If its an existing category, add the movie to existing list
    if (MovieCBO.ContainsKey("some_category"))
    {
        MovieCBO["some_category"].Add("new_movie_name");
    }
    //If its a new category, add category along the movie
    else
    {
        MovieCBO.Add("some_category", new List<string>() { "new_movie_name" });
    }
}

所有操作都将在恒定时间内完成。这比遍历列表中的所有项目并检查类别要快得多。

您可以将方法 addMovie 添加到 class CreateMovieList 以验证 MovieSolver 是否尚不存在并创建如有必要

public static void addMovie(String category, String movie) 
{
    var movieSolver = playerTargetList.Find(e => e.Category == category);
    if(movieSolver != null) 
    {
        var existingMovie = movieSolver.Movie.Find( e => e == movie);
        if (existingMovie == null)
            movieSolver.Movie.Add(movie);
    }
    else
        playerTargetList.Add(new MovieSolver  { Category = category, Movie = new List<string> { movie } }); 
}