c#填写空记录
问题描述:
需要一些帮助,我的foreach重新获得空记录并用“ - ”填补空缺。c#填写空记录
让我们说我们的情况下30分钟,45分钟,90分钟,120分钟,而不是60分钟:
它可以指望每个ID的总记录,让我们说最大的是5,30分钟,45分钟,60分钟,90分钟和120分钟。
如果有3个,那么它可以检查哪个丢失,并且可以填充“ - ”。
脚本的意思是一样的。
List<Treatment> treatment = new List<Treatment>();
treatment.Add(new Treatment { id = 1, treatmentNameId = 11, duration = "30", price = 30 });
treatment.Add(new Treatment { id = 1, treatmentNameId = 11, duration = "45", price = 45 });
treatment.Add(new Treatment { id = 1, treatmentNameId = 11, duration = "60", price = 60 });
treatment.Add(new Treatment { id = 1, treatmentNameId = 2, duration = "30", price = 30 });
//treatment.Add(new Treatment { id = 1, treatmentNameId = 2, duration = "45", price = 45 });
treatment.Add(new Treatment { id = 1, treatmentNameId = 2, duration = "60", price = 60 });
var newList = (from t in treatment
select t)
.AsQueryable().ToList();
List<List> newList= new List<List>();
foreach (var item in newList)
{
if (item.duration == "30")
{
newList.Add(new List { treatmentNameId = item.treatmentNameId, thirtyMin = "30" });
}
if (item.duration == "45")
{
newList.Add(new List { treatmentNameId = item.treatmentNameId, fortyFive= "45" });
}
if (item.duration == "60")
{
newList.Add(new List { treatmentNameId = item.treatmentNameId, sixty= "60" });
}
}
最终结果应该喜欢的东西作为,
id:1 30, 45, 60, -
id:2 30, - , 60, 90
id:3 - , 45, -, 90
等等
很多很多的帮助表示感谢。
答
我不会提供所有这些的非常详细的解释,但从概念上讲,我只是通过treatmentNameId进行分组,然后在SQL中执行与外连接非常相似的操作。如果组加入时间为空,我选择' - '而不是持续时间。为了简洁起见,使用匿名类型。
var durations = new[] {"15", "30", "45", "60"};
var results = treatments
.GroupBy(t => t.treatmentNameId).Select(group => new
{
treatmentNameId = group.Key,
durations = durations.GroupJoin(group, s => s, g => g.duration,
(s, grouping) => !grouping.Any() ? "-" : s)
});
foreach (var result in results)
{
Console.WriteLine(result.treatmentNameId + ": " + string.Join(", ", result.durations));
}
这导致:
11: -, 30, 45, 60
2: -, 30, -, 60
如果你有更具体的东西的问题,我很乐意进一步解释。