使用C#将行列表数据转换为列

问题描述 投票:0回答:1

我绑定了一个具有多个值的类列表。 我的清单是:

List<coveredoption> lst = new List<coveredoption>();

public class coveredoption
{      

    public string BType {get;set;}

    public string BName {get;set;}

    public string BValue {get;set;}

}

Coveredoption 是一个具有三个参数的类..

将多行数据添加到lst中。

现在我想使用 c# 将列表的行转换为列

提前感谢您的支持!例如。

Input list data.

Cov0 123 abc 
Cov0 234 afg

Expected result:

Cov0  Cov0
123   234
abc   afg

Please let me know if you need any other info..

我尝试使用矩阵,但这是单个列表,所以它不应该工作..

c# list generics
1个回答
0
投票

一个简单的解决方案是使用 string.Join 三次:

var input = new List<coveredoption>
{
    new coveredoption { BType = "Cov0", BName = "123", BValue = "abc" },
    new coveredoption { BType = "Cov0", BName = "234", BValue = "afg" }
};
        
Console.WriteLine(string.Join(" ", input.Select(x => x.BType)));
Console.WriteLine(string.Join(" ", input.Select(x => x.BName)));
Console.WriteLine(string.Join(" ", input.Select(x => x.BValue)));

但是每次调用 string.Join 都会循环遍历列表。因此,您有 3 个循环,而其中只需要一个。如果您的列表很大,这可能会成为一个问题。

更好的方法是使用三个字符串构建器,每一行一个。您循环列表并将属性附加到每个字符串生成器:

StringBuilder btypes = new StringBuilder();
StringBuilder bnames = new StringBuilder();
StringBuilder bvalues = new StringBuilder();
foreach(var item in input)
{
    btypes.Append(item.BType + " ");
    bnames.Append(item.BName + " ");
    bvalues.Append(item.BValue + " ");
}
Console.WriteLine(btypes);
Console.WriteLine(bnames);
Console.WriteLine(bvalues);

在线演示:https://dotnetfiddle.net/746M5U

© www.soinside.com 2019 - 2024. All rights reserved.