C#查找list集合及修改list集合里面的内容

2020-02-18 更新

修改集合里面的内容,首先要去了解,值类型和引用类型

list集合是引用类型,核心代码如下
//Book类
public class Book
{
    public string BookName { get; set; }
    public string BarCode { get; set; }
}
public void EditListBook()
{//原创来自 http://www.luofenming.com/show.aspx?id=ART2018020700001
    List<Book> listBook = new List<Book>();
    for(int i = 0; i < 10; i++)
    {
        Book book = new Book();
        book.BookName = "书名1" + i;
        book.BarCode = "条形码" + i;
        listBook.Add(book);
    }

    var books = listBook.Where(p => p.BarCode == "条形码6");//查询BarCode==条形码6;
    if (books != null && books.Count() > 0)
    {
        Book book = books.ToArray()[0];
        book.BookName = "罗分明";//修改书名
    }
    List<Book> l = listBook;// listBook 条形码6的书名
} 

评论