Sowmiya Pr
Sowmiya Pr

Reputation: 47

How to add multiple items in a list dynamically using linq in c#

I am trying to add multiple items in a list using console application in c#, But my list was adding with duplicate items.

Can anyone help me to resolve this isse?

Here is my piece of code.

public class Billionaire
{
    public String Name { get; set; }
    public String Country { get; set;}
    public int Income { get; set; }
}  

public static Billionaire billObj = new Billionaire();
public static List<Billionaire> Billionaires = new List<Billionaire>();

public static Billionaire billObj = new Billionaire();
public static List<Billionaire> Billionaires = new List<Billionaire>();

Upvotes: 0

Views: 911

Answers (1)

Anu Viswan
Anu Viswan

Reputation: 18155

You are working on the same instance of billObj each time you call the method addNewBillionaire. The List would keep a reference to the same copy, which is updated when you call the method the second time.

To resolve it,You need to reinitialize billObj in your method (as given in the comments).

public static void addNewBillionaire() 
{ 
    billObj = new Billionaire();
    Console.WriteLine("Enter name:"); 
    billObj.Name = Console.ReadLine(); 
    Console.WriteLine("Enter the income:"); 
    billObj.Income = int.Parse(Console.ReadLine()); 
    Console.WriteLine("Enter country:"); 
    billObj.Country = Console.ReadLine(); 
    Billionaires.Add(billObj); 
} 

If billObj isn't used elsewhere, a better approach would be to make billObj as local variable for the method

Upvotes: 1

Related Questions