C#,在 class 的列表中添加 class 的最简单方法是什么
C#,what is the simplest way to add a class in List of class
我有一个 class 多个记录 time.I 创建列表并创建 Statsand 对象,然后添加到我的列表中,但最近的记录被所有人复制。这是我的代码
List<Account> account = accountDao.All().Where(a => a.Role ==
Role.Distributor && a.ParentAccount.Id==1&&a.Active).ToList();
ViewBag.Accounts = account;
List<Stats> statsforRegions = new List<Stats>();
foreach (Account dist in account)
{
List<int> userIdss = new List<int>();
List<int> accountIdss = new List<int>();
Stats stt = new Stats();
stt=stats;
getUserIdsRecursive(dist, userIdss, accountIdss);
stt = calculate(stt, userIdss, accountIdss);
statsforRegions.Add(stt);
}
ViewBag.StatsForRegions = statsforRegions;
您正在创建一个新的 Stats
对象并将其分配给 stt
。
Stats stt = new Stats();
然后您将另一个对象 (stats
) 分配给 stt
,这意味着原始对象被丢弃。
stt = stats.
您的代码没有显示 stats
是什么,但我认为它是您所指的 "recent record"。
这是将对象添加到列表的基本示例
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<MyObject> MyList = new List<MyObject>();
for (int x = 1; x <= 10; x++)
{
MyObject obj = new MyObject();
obj.Id = x;
MyList.Add(obj);
}
//now show the list
foreach(MyObject obj in MyList)
{
Console.WriteLine(obj.Id.ToString());
}
}
}
public class MyObject
{
public int Id {get;set;}
}
我也给你写了一篇fiddlehttps://dotnetfiddle.net/cnNiI5
我认为您的 calculate
函数返回的值与
相同
stats
不变。
stt=stats;
getUserIdsRecursive(dist, userIdss, accountIdss);
stt = calculate(stt, userIdss, accountIdss);
我有一个 class 多个记录 time.I 创建列表并创建 Statsand 对象,然后添加到我的列表中,但最近的记录被所有人复制。这是我的代码
List<Account> account = accountDao.All().Where(a => a.Role ==
Role.Distributor && a.ParentAccount.Id==1&&a.Active).ToList();
ViewBag.Accounts = account;
List<Stats> statsforRegions = new List<Stats>();
foreach (Account dist in account)
{
List<int> userIdss = new List<int>();
List<int> accountIdss = new List<int>();
Stats stt = new Stats();
stt=stats;
getUserIdsRecursive(dist, userIdss, accountIdss);
stt = calculate(stt, userIdss, accountIdss);
statsforRegions.Add(stt);
}
ViewBag.StatsForRegions = statsforRegions;
您正在创建一个新的 Stats
对象并将其分配给 stt
。
Stats stt = new Stats();
然后您将另一个对象 (stats
) 分配给 stt
,这意味着原始对象被丢弃。
stt = stats.
您的代码没有显示 stats
是什么,但我认为它是您所指的 "recent record"。
这是将对象添加到列表的基本示例
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<MyObject> MyList = new List<MyObject>();
for (int x = 1; x <= 10; x++)
{
MyObject obj = new MyObject();
obj.Id = x;
MyList.Add(obj);
}
//now show the list
foreach(MyObject obj in MyList)
{
Console.WriteLine(obj.Id.ToString());
}
}
}
public class MyObject
{
public int Id {get;set;}
}
我也给你写了一篇fiddlehttps://dotnetfiddle.net/cnNiI5
我认为您的 calculate
函数返回的值与
stats
不变。
stt=stats;
getUserIdsRecursive(dist, userIdss, accountIdss);
stt = calculate(stt, userIdss, accountIdss);