Linq填充一个类的值

时间:2015-07-28 10:47:23

标签: c# .net linq .net-4.0

我有一个班级

public class Row : IExtensible
{
    public Row();

    [ProtoMember(1, IsRequired = true, Name = "key", DataFormat = DataFormat.Default)]
    public byte[] key { get; set; }

    [ProtoMember(2, Name = "values", DataFormat = DataFormat.Default)]
    public List<Cell> values { get; }
}

我可以使用以下方法手动填充:

编辑: //列和数据是样本byte []值

CellSet.Row row = new CellSet.Row { key = sampleKey };
Cell value = new Cell { column = column1, data = data1 };
row.values.Add(value);

我需要在LINQ中填充这些值,这是我一直在尝试的:

var result =
(
    from a in firstrow
    let valuesset = a.Split(',')
    from l in valuesset
    select new CellSet.Row
    {
        key = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()),
        //values = new List<Cell>() //Not possible since only get is there
    }
).ToList();

如何向对象CellSet.Row添加值?

我也试过这个

//Edit:
//Read the xml file row by row and process it

var result =
(
    from a in firstrow
    let valuesset = a.Split(',')
    from l in valuesset
    select new CellSet.Row
    {
        key = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()),
        //values = new List<Cell>() //Not possible since only get is there
    }.values.Add(value12)
).ToList();

在以下值中出现错误:

  

在IEnumerable&lt;&gt;

的后续from子句中不允许使用'string []'类型的表达式

1 个答案:

答案 0 :(得分:2)

你会做这样的事情:

Func<byte[], IEnumerable<Cell>, Row> create =
    (k, cs) =>
    {
        CellSet.Row row = new CellSet.Row { key = k };
        row.values.AddRange(cs);
        return row;
    };

var result =
(
    from a in firstrow
    let valuesset = a.Split(',')
    from l in valuesset
    select create(
        Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()),
        new [] { value12 })
).ToList();

现在,由于您的代码并不清楚它应该如何正常工作,因此答案也不存在。但这应该给你基本的想法。