Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a copy of data instead of a reference using linq/lambda in c#?

Tags:

c#

lambda

linq

Is there an easy way to basically just get a copy of the data instead of a reference using this method? I tried .ToArray().Where() but that still seems to pass a reference.

Example:

static void Main(string[] args)
{
    List<ob> t = new List<ob>();
    t.Add(new ob() { name = "hello" });
    t.Add(new ob() { name = "test" });

    ob item = t.Where(c => c.name == "hello").First();

    // Changing the name of the item changes the original item in the list<>
    item.name = "burp";

    foreach (ob i in t)
    {
        Console.WriteLine(i.name);
    }

    Console.ReadLine();
}

public class ob
{
    public string name;
}
like image 333
Josh Avatar asked Jan 04 '12 09:01

Josh


People also ask

How do you copy a list without references?

To copy an existing list to another one without reference, you can use the copy() method. In this example, we copied the first list to the second list using the copy() function. The second list is a separate list, not a reference.

How do I return a single value from a list using LINQ?

var fruit = ListOfFruits. FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0; This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First().

What are the different types of data sources that LINQ can retrieve data from?

In the same way, LINQ is a structured query syntax built in C# and VB.NET to retrieve data from different types of data sources such as collections, ADO.Net DataSet, XML Docs, web service and MS SQL Server and other databases.

What is difference between LINQ and Lambda expression?

Language Integrated Query (LINQ) is feature of Visual Studio that gives you the capabilities yo query on the language syntax of C#, so you will get SQL kind of queries. And Lambda expression is an anonymous function and is more of a like delegate type.


1 Answers

You need to create a copy of your ob yourself - it's not something LINQ provides.

like image 153
Tim Rogers Avatar answered Oct 19 '22 20:10

Tim Rogers