简体   繁体   中英

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

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.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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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