过去几个小时我一直对这个问题感到困惑,希望你能帮助我。
我有一个填充数据的列表(请参阅class:allItems),但我想分割数据,因此类项包含所有内容,其中包含子项目的项目中的公共列表。
在这个代码片段中发生的事情是,在for循环期间,项目被添加了相同的值到日期列表,这是我在难以尝试向日期列表添加正确数量的条目给出多少次allStats列表中的同一周数字。
任何帮助都将不胜感激,谢谢。
public class allItems
{
public DateTime PunchInDate { get; set; }
public DateTime PunchOutDate { get; set; }
public DayOfWeek DayOfWeek { get; set; }
public int WeekNumber { get; set; }
public int MonthNumber { get; set; }
public bool PunchedInLate { get; set; }
public bool PunchedOutLate { get; set; }
}
public class items
{
public int WeekNumber { get; set; }
public int MonthNumber { get; set; }
public List<subItems> Days { get; set; }
}
public class subItems
{
public bool PunchedInLate { get; set; }
public bool PunchedOutLate { get; set; }
public DateTime PunchInDate { get; set; }
public DateTime PunchOutDate { get; set; }
public DayOfWeek DayOfWeek { get; set; }
}
protected int getNumberOfWeeks(List<allItems> list, int numberToFind)
{
List<allItems> results = list.FindAll(
delegate(allItems ai)
{
return ai.WeekNumber == numberToFind;
}
);
return results.Count;
}
public List<items> getStats(string userId, string type)
{
List<allItems> allStats = getAllStats(userId, "week");
List<items> stats = new List<items>();
foreach (allItems allItem in allStats)
{
items item = new items();
subItems subItem = new subItems();
List<subItems> Days = new List<subItems>();
item.MonthNumber = allItem.MonthNumber;
item.WeekNumber = allItem.WeekNumber;
item.Days = Days;
int numberOfWeeks = getNumberOfWeeks(allStats, allItem.WeekNumber);
for (int i = 0; i < numberOfWeeks; i++)
{
subItem.DayOfWeek = allItem.DayOfWeek;
subItem.PunchedInLate = allItem.PunchedInLate;
subItem.PunchedOutLate = allItem.PunchedOutLate;
subItem.punchInDate = allItem.PunchInDate;
subItem.PunchOutDate = allItem.PunchOutDate;
Days.Add(subItem);
}
items result = stats.Find(week => week.WeekNumber == allItem.WeekNumber);
if (result == null)
{
stats.Add(item);
}
}
return stats;
}
答案 0 :(得分:3)
听起来你可以用linq做到这一点:
var allItemsList = new List<allItems>() { ... fill in items ... };
var asItems =
from item in allItemsList
group item by new { week = item.weekNumber, month = item.monthNumber } into byWeekMonth
select new items()
{
weekNumber = byWeekMonth.Key.week,
monthNumber = byWeekMonth.Key.month,
days = byWeekMonth.Select(si =>
new subItems()
{
punchedInLate = si.punchedInLate,
punchedOutLate = si.punchedOutLate,
// etc, other fields
}).ToList()
};