提问人:Lifewithsun 提问时间:10/19/2023 最后编辑:Lifewithsun 更新时间:10/21/2023 访问量:103
动态转置列表对象
dynamically transpose list object
问:
我有workItemStateCalculatedTimes列表,如下所示
public class WorkItemStateCalculatedTime
{
public string State { get; set; }
public double TimeinHrs { get; set; }
}
并且需要将其转置以获得低于所需输出的输出,其中每行的第一列值将转换为列,并且 timeinhrs 将是该列的值
状态列可以有多行。我尝试使用动态列表,但没有得到所需的输出。
List<dynamic> data = new List<dynamic>();
foreach (var item in workItemStateCalculatedTimes)
{
data.Add(item.State);
}
答:
1赞
Martheen
10/19/2023
#1
这可以使用 ExpandoObject 完成,添加列,然后将对象转换为动态对象。
var calculated = new[] { new {State = "New",TimeinHrs = 4.6 }, new { State = "Todo", TimeinHrs = 5.4 }, new { State = "Done", TimeinHrs = 8.5 } }.ToList();
var expTransposed = new ExpandoObject();
calculated.ForEach(c => expTransposed.TryAdd(c.State, c.TimeinHrs));
dynamic dynTransposed = expTransposed;
Console.WriteLine(dynTransposed.New); //would output 4.6
您仍然可以使用 循环遍历所有列。expTransposed
评论
0赞
Lifewithsun
10/19/2023
我收到错误“以下方法或属性之间的调用不明确:'system.collection.generic.collectionextension.TryAdd 和 system.collection.generic.Dictionaryextension.TryAdd'”
0赞
Martheen
10/19/2023
State 和 TimeinHrs 的类型、.NET 版本和包含的命名空间是什么?我无法复制那个模棱两可的电话 dotnetfiddle.net/EcFoJb
0赞
Martheen
10/19/2023
它们与我的匿名示例是相同的成员类型,正如您在小提琴中看到的那样,我没有遇到模棱两可的呼叫
0赞
Lifewithsun
10/19/2023
由于 Microsoft.VisualStudio.Services.Common.dll 冲突,我收到错误。我使用了dll的内联引用,问题就解决了。
0赞
DebugCode
10/21/2023
#2
我有这样的东西,请检查一次。
public class WorkItemStateCalculatedTime
{
public string State { get; set; }
public double TimeinHrs { get; set; }
}
public class Program
{
static void Main()
{
List<WorkItemStateCalculatedTime> workItemStateCalculatedTimes = new List<WorkItemStateCalculatedTime>
{
new WorkItemStateCalculatedTime { State = "New", TimeinHrs = 2.5 },
new WorkItemStateCalculatedTime { State = "ToDo", TimeinHrs = 3.0 },
new WorkItemStateCalculatedTime { State = "Done", TimeinHrs = 1.5 },
new WorkItemStateCalculatedTime { State = "WIP", TimeinHrs = 4.5 },
};
var distinctStates = workItemStateCalculatedTimes.Select(w => w.State).Distinct().ToList();
DataTable transposedTable = new DataTable();
foreach (var state in distinctStates)
{
transposedTable.Columns.Add(state, typeof(double));
}
var groupedData = workItemStateCalculatedTimes.GroupBy(w => w.State);
foreach (var group in groupedData)
{
DataRow newRow = transposedTable.NewRow();
newRow[group.Key] = group.Sum(w => w.TimeinHrs);
transposedTable.Rows.Add(newRow);
}
Console.WriteLine("Transposed Data:");
foreach (DataRow row in transposedTable.Rows)
{
Console.Write("State: ");
foreach (var state in distinctStates)
{
Console.Write($"{state}: {row[state]} ");
}
Console.WriteLine();
}
}
}
评论
data
data.New
data.Todo
data.Done
data.New
4.6