Подтвердить что ты не робот

Редактирование элемента в списке <T>

Как отредактировать элемент в списке в приведенном ниже коде:

List<Class1> list = new List<Class1>();

int count = 0 , index = -1;
foreach (Class1 s in list)
{
    if (s.Number == textBox6.Text)
        index = count; // I found a match and I want to edit the item at this index
    count++;
}

list.RemoveAt(index);
list.Insert(index, new Class1(...));
4b9b3361

Ответ 1

После добавления элемента в список его можно заменить, написав

list[someIndex] = new MyClass();

Вы можете изменить существующий элемент в списке, написав

list[someIndex].SomeProperty = someValue;

EDIT. Вы можете написать

var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);

Ответ 2

Вам не нужно использовать linq, поскольку List<T> предоставляет методы для этого:

int index = lst.FindLastIndex(c => c.Number == textBox6.Text);
if(index != -1)
{
    lst[index] = new Class1() { ... };
}

Ответ 3

public changeAttr(int id)
{
    list.Find(p => p.IdItem == id).FieldToModify = newValueForTheFIeld;
}

С

  • IdItem - это идентификатор элемента, который вы хотите изменить

  • FieldToModify - это поле элемента, который вы хотите обновить.

  • NewValueForTheField - это то, что новое значение.

(Он отлично работает для меня, проверен и реализован)

Ответ 4

  1. Вы можете использовать метод FindIndex(), чтобы найти индекс элемента.
  2. Создать новый элемент списка.
  3. Переопределить индексированный элемент новым элементом.

List<Class1> list = new List<Class1>();

int index = list.FindIndex(item => item.Number == textBox6.Text);

Class1 newItem = new Class1();
newItem.Prob1 = "SomeValue";

list[index] = newItem;

Ответ 5

class1 item = lst[index];
item.foo = bar;

Ответ 6

       Console.WriteLine("Edit ProductList using Id: ");
                Console.WriteLine("Enter ProductId: ");
                int id = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Enter Name: ");
                string name = Console.ReadLine();
                Console.WriteLine("Enter Brand: ");
                string Brandname = Console.ReadLine();
                Console.WriteLine("Enter Price: ");
                int price = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Enter Quantity: ");
                int Quantity = Convert.ToInt32(Console.ReadLine());
                var itemToEdit = list.Find(r => r.ProductId == id);
                list.Remove(itemToEdit);
                Console.WriteLine($"{itemToEdit.ProductId=id}{itemToEdit.Name=name}



    class Program
    {
        public static List<Product> list;
        static void Main(string[] args)
        {

            list = new List<Product>() { new Product() { ProductId=1, Name="Nike 12N0",Brand="Nike",Price=12000,Quantity=50},
                 new Product() { ProductId =2, Name = "Puma 560K", Brand = "Puma", Price = 120000, Quantity = 55 },
                 new Product() { ProductId=3, Name="WoodLand V2",Brand="WoodLand",Price=21020,Quantity=25},
                 new Product() { ProductId=4, Name="Adidas S52",Brand="Adidas",Price=20000,Quantity=35},
                 new Product() { ProductId=5, Name="Rebook SPEED2O",Brand="Rebook",Price=1200,Quantity=15}};
 {itemToEdit.Brand=Brandname}{itemToEdit.Price=price}{ itemToEdit.Quantity=Quantity}");
                var query2 = from x in list select x;
                foreach (var item in query2)
                {
                    Console.WriteLine($"{item.ProductId}{item.Name}{item.Brand}{item.Price}{ item.Quantity}");
                }
            }

        }
    }