简体   繁体   中英

List Manipulation in C# using Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace ConsoleApplication1
{

    public class Class1  
    {
       static void Main(string[] args)
       {
           List<Car> mylist = new List<Car>();
           Car car1;
           Car car2;
           Car car3;

           car1 = new Car()
           {
               make = "Honda",
               id = 1
           };
           car2 = new Car()
           {
               make = "toyota",
               id = 2
           };

           car3 = new Car()
           {
              make = "Honda",
              id = 3,
              color = "red"
           };

           mylist.Add(car1);
           mylist.Add(car2);
           **////mylist.Where(p => p.id == 1).SingleOrDefault() = car3;**
        }        
    }

    public class Car
    {
        public int id { get; set; }
        public string make { get; set; }
        public string color { get; set; }

    }
}

How can I update the list by replacing the honda car of Id 1 with honda car with Id 3 in the best way.

Everything leppie said - plus:

int index = mylist.FindIndex(p => p.id == 1);
if(index<0) {
    mylist.Add(car3);
} else {
    mylist[index] = car3;
}

This just uses the existing FindIndex to locate a car with id 1, then replace or add it. No LINQ; no SQL - just a lambda and List<T> .

If you wanted to do an update to multiple elements...

foreach (var f in mylist.FindAll(x => x.id == 1))  
{    
    f.id = car3.id;  
    f.color = car3.color;  
    f.make = car3.make;  
}  

This is not LINQ2SQL.

Also, LINQ is not used for updating, only to query for objects.

You can use this way :

(from car in mylist
where car.id == 1
select car).Update(
car => car.id = 3);

My reference is this website . Or following is the code for Update method

public static void Update<T>(this IEnumerable<T> source, params Action<T>[] updates)
{
    if (source == null)
        throw new ArgumentNullException("source");

    if (updates == null)
        throw new ArgumentNullException("updates");

    foreach (T item in source)
    {
        foreach (Action<T> update in updates)
        {
            update(item);
        }
    }
}
//Item class
Class Item
{
   public string Name { get; set; }
}

List < Item > myList = new List< Item >()

//Add item to list
Item item = new Item();
item.Name = "Name";

myList.Add(Item);

//Find the item with the name prop

Item item2 = myList.Find(x => x.Name == "Name");

if(item2 != null)
   item.Name = "Changed";

As Leppie said, LINQ is for querying rather than updating. However, that can be used to build a new list:

mylist = new List<Car>(from car in mylist select car.id == 1? car3 : car)

That is if you want to use LINQ. It's nice and short code, of course, but a bit less efficient than Marc Gravell's suggestion, as it effectively creates a new list, rather than updating the old one.

Just one question, why do I have to write a Update function for something that seems so basic for a list? There should be standard methods for Lists like Add(), Delete(), Edit(), Insert(), Replace() ....Find()

List<AvailabilityIssue> ai = new List<AvailabilityIssue>();

ai.AddRange(
    (from a in db.CrewLicences
        where
            a.ValidationDate <= ((UniversalTime)todayDate.AddDays(30)).Time &&
            a.ValidationDate >= ((UniversalTime)todayDate.AddDays(15)).Time
        select new AvailabilityIssue()
        {
            crewMemberId = a.CrewMemberId,
            expirationDays = 30,
            Name = a.LicenceType.Name,
            expirationDate = new UniversalTime(a.ValidationDate).ToString("yyyy-MM-dd"),
            documentType = Controllers.rpmdataController.DocumentType.Licence
        }).ToList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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