简体   繁体   English

如何在c#中使用linq动态添加列表中的多个项目

[英]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.我正在尝试使用 c# 中的控制台应用程序在列表中添加多个项目,但我的列表添加了重复的项目。

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

You are working on the same instance of billObj each time you call the method addNewBillionaire .您正在使用的同一个实例billObj每次调用方法时addNewBillionaire The List would keep a reference to the same copy, which is updated when you call the method the second time. List 将保留对同一副本的引用,该副本在您第二次调用该方法时更新。

To resolve it,You need to reinitialize billObj in your method (as given in the comments).要解决它,您需要在您的方法中重新初始化 billObj (如评论中所述)。

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如果billObj不在其他地方使用,更好的方法是将 billObj 作为方法的局部变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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