简体   繁体   English

C#和Linq查询对象[,]

[英]c# and Linq query to object[,]

I have a list of query results, each containing objects different from the others. 我有一个查询结果列表,每个查询结果都包含与其他对象不同的对象。 I have one type per data set. 每个数据集都有一种类型。

var myQueryresult = _myContext.TableA
    .Where(a => a.IsToBeProcessed)
    .Select(x => new { ColumnA = x.FieldA, ColumnB =  x.FieldB })
    .ToList();

The end goal is to store this data in an Excel sheet using the 最终目标是使用以下命令将数据存储在Excel工作表中:

Range firstCell = sheet.Cells[1, 1];
Range lastCell = sheet.Cells[data.GetLength(0) + 1, data.GetLength(1)];
sheet.Range[firstCell, lastCell].Value2 = myObjectArrayofObjectArrays;

I can't seem to find any way to do this but looping on each row of the result. 我似乎找不到任何方法,但是在结果的每一行上循环。

You can use the Excel library's NamedRange.get_Resize Method as well as NamedRange.set_Value Method (Object, Object) as follows: 您可以使用Excel库的NamedRange.get_Resize方法以及NamedRange.set_Value方法(对象,对象) ,如下所示:

Excel.Range testRng = (Excel.Range)sheet.Cells[1, 1];
testRng = testRng.get_Resize(data.GetLength(0), data.GetLength(1));
testRng.set_Value(Excel.XlRangeValueDataType.xlRangeValueDefault, myObjectArrayofObjectArrays);

EDIT 编辑

I misunderstood the requirements. 我误解了要求。 For your first part it does seem like a loop going through each element is the best method. 对于您的第一部分,似乎遍历每个元素的循环似乎是最好的方法。

you can turn your set of data into a datatable via json 您可以通过json将数据集转换为数据表

var json = JsonConvert.SerializeObject(results);
var table = (DataTable)JsonConvert.DeserializeObject(json, typeof(DataTable))

and then rely on your engine of choice to output the datatable into excel ready format 然后依靠您选择的引擎将数据表输出为excel就绪格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM