List Manipulation in C# using Linq

后端 未结 8 535
庸人自扰
庸人自扰 2020-12-24 12:24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace ConsoleApplication1
{

    public cla         


        
相关标签:
8条回答
  • 2020-12-24 12:53

    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>.

    0 讨论(0)
  • 2020-12-24 12:56

    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;  
    }  
    
    0 讨论(0)
  • 2020-12-24 12:57
    //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";
    
    0 讨论(0)
  • 2020-12-24 12:57

    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()

    0 讨论(0)
  • 2020-12-24 12:57
    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());
    
    0 讨论(0)
  • 2020-12-24 13:07

    This is not LINQ2SQL.

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

    0 讨论(0)
提交回复
热议问题