Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Manipulation in C# using Linq

Tags:

c#

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.

like image 618
Learner Avatar asked Dec 12 '08 04:12

Learner


People also ask

What is list manipulation?

Reads a list from a file on a target machine into a list variable.

Does C have a list function?

C and its standard library don't offer any list specific functions.

What are the two common list manipulation functions?

The list function creates a list from a set of s-expressions. It takes a variable number of arguments, and merely formulates those arguments into a list. Several other useful list manipulations are provided as well: append , reverse , and length .

Why use lists R?

The list is one of the most versatile data types in R thanks to its ability to accommodate heterogenous elements. A single list can contain multiple elements, regardless of their types or whether these elements contain further nested data. So you can have a list of a list of a list of a list of a list …


1 Answers

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

like image 120
Marc Gravell Avatar answered Oct 02 '22 12:10

Marc Gravell