LINQ - extract properties values into arrays - linq

I have an List of objects and I need to get the values of each property into arrays without iterating the list more than once.
Here is the current code.
I can't seem to figure out if I can do this using Linq and only iterate the list once.
var numberOfItems = invoiceItemNotes.Count;
var postingRcNum = new decimal [numberOfItems];
var postingLocNum = new decimal[numberOfItems];
var invoiceNum = new decimal[numberOfItems];
var orderItemLineNum = new decimal[numberOfItems];
var seqNum = new decimal[numberOfItems];
var text = new string[numberOfItems];
int index = 0;
foreach (var invoiceItemNote in invoiceItemNotes)
{
postingRcNum[index] = invoiceItemNote.POSTING_RC_NUM;
postingLocNum[index] = invoiceItemNote.POSTING_LOC_NUM;
invoiceNum[index] = invoiceItemNote.INVOICE_NUM;
orderItemLineNum[index] = invoiceItemNote.ORDER_ITEM_LINE_NUM;
seqNum[index] = invoiceItemNote.SEQ_NUM;
text[index] = invoiceItemNote.TEXT;
index++;
}
using (var cmd = connection.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = InvoiceInsertCommands.InsertItemNote;
cmd.BindByName = true;
cmd.UpdatedRowSource = UpdateRowSource.None;
cmd.ArrayBindCount = numberOfItems;
cmd.Parameters.Add(InvoiceItemNoteParameters.PostingRcNum, OracleDbType.Decimal, postingRcNum, ParameterDirection.Input);
cmd.Parameters.Add(InvoiceItemNoteParameters.PostingLocNum, OracleDbType.Decimal, postingLocNum, ParameterDirection.Input);
cmd.Parameters.Add(InvoiceItemNoteParameters.InvoiceNum, OracleDbType.Decimal, invoiceNum, ParameterDirection.Input);
cmd.Parameters.Add(InvoiceItemNoteParameters.OrderItemLineNum, OracleDbType.Decimal, orderItemLineNum, ParameterDirection.Input);
cmd.Parameters.Add(InvoiceItemNoteParameters.SeqNum, OracleDbType.Decimal, seqNum, ParameterDirection.Input);
cmd.Parameters.Add(InvoiceItemNoteParameters.Text, OracleDbType.Varchar2, text, ParameterDirection.Input);
cmd.ExecuteNonQuery();
}

Simple.
object[] invoiceItemNotes = new object[10];
int index = 0;
var invoiceItemNote = invoiceItemNotes[index];

Related

Save ID two columns Laravel

I want to save the ID of a new Sale(); in $sale->voucher_series, how can I achieve this?
$sale = new Sale();
$sale->customerid = $request->customerid;
$sale->userid = \Auth::user()->id;
$sale->proof_type = $request->proof_type;
$sale->voucher_series = $request->saleId;
$sale->date_time = $mytime->toDateString();
$sale->total = $request->total;
$sale->status = 'Registered';
$sale->save();
If your voucher_series column is nullable field then it will work.
$sale = new Sale ();
$sale->customerid = $request->customerid;
$sale->userid = \Auth :: user()->id;
$sale->proof_type = $request->proof_type;
$sale->date_time = $mytime->toDateString ();
$sale->total = $request->total;
$sale->status = 'Registered';
$sale->save();
$sale->voucher_series = $sale->id;

Extracting Ngrams with ml.net

I have the following pipeline:
var mlContext = new MLContext();
var data = mlContext.Data.LoadFromEnumerable(new[]
{
new Input {Message = "one two three one two three"},
new Input {Message = "one two"},
new Input {Message = "two three"}
});
var pipeline =
mlContext.Transforms.Text.FeaturizeText("TextFeatures", "Message")
.Append(mlContext.Transforms.Text.TokenizeCharacters(
"MessageTokens", "Message"))
.Append(mlContext.Transforms.Text.ProduceNgrams(
"MessageNgrams", "MessageTokens", 2));
var transformedData = pipeline.Fit(data).Transform(data);
"MessageNgrams" column after pipe execution contains float vectors. How can I get actual Ngrams i.e. "one two", "two tree"?
List<string> getNgram(string str, int nsize)
{
var mlContext = new MLContext();
var dataview = mlContext.Data.LoadFromEnumerable(new List<TextData>() { new TextData { Text = str } });
var textPipeline = mlContext.Transforms.Text.TokenizeIntoWords("Tokens", "Text")
.Append(mlContext.Transforms.Conversion.MapValueToKey("Tokens"))
.Append(mlContext.Transforms.Text.ProduceNgrams("NgramFeatures", "Tokens",
ngramLength: nsize,
useAllLengths: false,
weighting: NgramExtractingEstimator.WeightingCriteria.Tf));
var textTransformer = textPipeline.Fit(dataview);
var transformedDataView = textTransformer.Transform(dataview);
VBuffer<ReadOnlyMemory<char>> slotNames = default;
transformedDataView.Schema["NgramFeatures"].GetSlotNames(ref slotNames);
var NgramFeaturesColumn = transformedDataView.GetColumn<VBuffer<float>>(transformedDataView.Schema["NgramFeatures"]);
var ngrams = slotNames.GetValues().ToArray().Select(x=>x.Span.ToString().Replace('|',' '));
return ngrams.ToList();
}
Here is a code snippet which works for my SCDA, should be very similar or give you hints on how to achieve it.
var slotLabelBuffer = default(VBuffer<ReadOnlyMemory<char>>);
transformedData.Schema["MessageNgrams"].GetSlotNames(ref slotLabelBuffer);
var slotLabels = new Dictionary<int, string>();
for (int i = 0; i < slotLabelBuffer.Length; i++)
slotLabels.Add(i, slotLabelBuffer.GetItemOrDefault(i).ToString());
Index of slotLabels corresponds to your float vector.

Must declare the scalar variable "#historyId" exception

I have a working raw Sql command execution
using (var cmd = SqlUtils.CreateSqlCommand(cmdText, sqlConn))
{
cmd.Parameters.Add(new SqlParameter("historyId", SqlDbType.Int)).Value = AAverage.CashFlowRelevantHistoryId;
cmd.Parameters.Add(new SqlParameter("nodeId", SqlDbType.Int)).Value = AAverage.CashNodeId;
cmd.Parameters.Add(new SqlParameter("denomId", SqlDbType.Int)).Value = AAverage.DenominationId;
cmd.Parameters.Add(new SqlParameter("dayId", SqlDbType.Int)).Value = AAverage.CashFlowDayCategoryId;
cmd.Parameters.Add(new SqlParameter("hour", SqlDbType.Int)).Value = AAverage.Hour;
cmd.Parameters.Add(new SqlParameter("type", SqlDbType.Int)).Value = AAverage.ValueType;
cmd.Parameters.Add(new SqlParameter("average", SqlDbType.Real)).Value = AAverage.AverageDerivative;
using (var reader = cmd.ExecuteReader())
if (reader.HasRows && reader.Read())
{
IDataRecord record = (IDataRecord)reader;
AAverage.Id = record.GetInt32ByName("Id");
}
}
but if I've changed it to use SqlQuery method, I get the error in the subject:
StringBuilder cmdText = new StringBuilder();
cmdText.AppendLine("INSERT INTO CashFlowAverageDerivatives");
cmdText.AppendLine(" (CashFlowRelevantHistoryId, CashNodeId, DenominationId, CashFlowDayCategoryId, Hour, ValueType, AverageDerivative)");
cmdText.AppendLine("VALUES");
cmdText.AppendLine(" (#historyId, #nodeId, #denomId, #dayId, #hour, #type, #average)");
cmdText.AppendLine("SELECT Id FROM CashFlowAverageDerivatives WHERE ##ROWCOUNT > 0 and Id = scope_identity()");
AAverage.Id = ADbContext.Database.SqlQuery<int>(
cmdText.ToString(),
new SqlParameter("historyId", SqlDbType.Int).Value = AAverage.CashFlowRelevantHistoryId,
new SqlParameter("nodeId", SqlDbType.Int).Value = AAverage.CashNodeId,
new SqlParameter("denomId", SqlDbType.Int).Value = AAverage.DenominationId,
new SqlParameter("dayId", SqlDbType.Int).Value = AAverage.CashFlowDayCategoryId,
new SqlParameter("hour", SqlDbType.Int).Value = AAverage.Hour,
new SqlParameter("type", SqlDbType.Int).Value = AAverage.ValueType,
new SqlParameter("average", SqlDbType.Real).Value = AAverage.AverageDerivative
).First<int>();
and I have no idea why. If I tried to rename "historyId" in Sql text to something else, exception reports this new name. It seems like parameter definition was missing or misspelled, but list of parameters has been copy&pasted, VS IDE search command finds it, prefix "#" does not matter...
Sure I can live with my working version, but I'm learning EF and it tease me I'm not able to solve this
You were sending the sql parameter as value directly.
When you did this
new SqlParameter("historyId", SqlDbType.Int).Value = AAverage.CashFlowRelevantHistoryId
You actually sent a value of AAverage.CashFlowRelevantHistoryId, not a SqlParameter.
Try changing it with this and see if it works.
AAverage.Id = ADbContext.Database.SqlQuery<int>(
cmdText.ToString(),
new SqlParameter("historyId", AAverage.CashFlowRelevantHistoryId),
new SqlParameter("nodeId", AAverage.CashNodeId),
new SqlParameter("denomId", AAverage.DenominationId),
new SqlParameter("dayId", AAverage.CashFlowDayCategoryId),
new SqlParameter("hour", AAverage.Hour),
new SqlParameter("type", AAverage.ValueType),
new SqlParameter("average", AAverage.AverageDerivative)
).First<int>();
Or this
AAverage.Id = ADbContext.Database.SqlQuery<int>(
cmdText.ToString(),
new SqlParameter("historyId", SqlDbType.Int) { Value = AAverage.CashFlowRelevantHistoryId },
new SqlParameter("nodeId", SqlDbType.Int) { Value = AAverage.CashNodeId },
new SqlParameter("denomId", SqlDbType.Int) { Value = AAverage.DenominationId },
new SqlParameter("dayId", SqlDbType.Int) { Value = AAverage.CashFlowDayCategoryId },
new SqlParameter("hour", SqlDbType.Int) { Value = AAverage.Hour },
new SqlParameter("type", SqlDbType.Int) { Value = AAverage.ValueType },
new SqlParameter("average", SqlDbType.Real) { Value = AAverage.AverageDerivative }
).First<int>();

alias with space in columns using linq and gridview to export excel

I need to export Excel and I'm using MVC4
This is my code
var co = from c in context.AN_COMPANY
orderby c.COMPANY_DESCR
select c;
List<AN_COMPANY_EXT> societa_list = new List<AN_COMPANY_EXT>();
foreach (var o in co)
{
AN_COMPANY_EXT c_ex = new AN_COMPANY_EXT(o);
societa_list.Add(c_ex);
}
GridView gv = new GridView();
gv.DataSource = (from d in societa_list
select new { Codice = d.ID_COMPANY, Descrizione = d.COMPANY_DESCR, SAP_Alias = d.COMPANY_SAP_ALIAS, Booking_Company = d.IS_BOOKING_COMPANY });
gv.DataBind();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=AnagraficaSocieta.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("Index");
How can I set column name with a space, for example "SAP ALIAS" instead of SAP_ALIAS?

Error in View when i try use inherit Linq magic

I try make table where i keep children-parent data. Ofc root of parents is "0" and here in table can by many roots. When i try make this work i got error.
Unable to create a constant value of type 'Projekty03.ViewsModels.ParagrafViewModel'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
public ViewResult Index()
{
List<ParagrafViewModel> _paragrafparent = new List<ParagrafViewModel>();
_paragrafparent.Add(new ParagrafViewModel { ParagrafID = 0, ParagrafNazwa = "Root" });
var _paragrafparent2 = from pr in paragrafRepository.All
orderby pr.ParagrafID
select new ParagrafViewModel
{
ParagrafID = pr.ParagrafID,
ParagrafNazwa = pr.ParagrafNazwa
};
var _paragrafparent3 = _paragrafparent.Concat(_paragrafparent2).AsEnumerable();
var paragraf = from par in paragrafRepository.All
join rodzic_p in _paragrafparent3
on par.ParagrafParent equals rodzic_p.ParagrafID
orderby par.ParagrafParent, par.ParagrafID
select new ParagrafViewModel
{
ParagrafID = par.ParagrafID,
ParagrafNazwa = par.ParagrafNazwa,
ParagrafParent = par.ParagrafParent,
ParagrafCzynny = par.ParagrafCzynny,
ParagrafWplyw = par.ParagrafWplyw,
ParagrafParentNazwa = rodzic_p.ParagrafNazwa
};
return View(paragraf);
}
I believe is sht wrong with my poor magic LINQ think. How resolve this ?
Ok here is a answer for my own question. Im sure is not a pretty solution but ...
public ViewResult Index()
{
List<ParagrafViewModel> _paragrafparent = new List<ParagrafViewModel>();
_paragrafparent.Add(new ParagrafViewModel { ParagrafID = 0, ParagrafNazwa = "Root", ParagrafCzynny=false, });
var _paragrafparent2 = from pr in paragrafRepository.AllIncluding(paragraf => paragraf.WniosekPodzial)
orderby pr.ParagrafID
select new ParagrafViewModel
{
ParagrafID = pr.ParagrafID,
ParagrafNazwa = pr.ParagrafNazwa,
ParagrafParent = pr.ParagrafParent,
ParagrafCzynny = pr.ParagrafCzynny,
ParagrafWplyw = pr.ParagrafWplyw,
WniosekPodzialNazwa = pr.WniosekPodzial.WniosekPodzialNazwa
};
var _paragrafparent3 = _paragrafparent.Concat(_paragrafparent2).AsEnumerable();
var paragrafModel = from par in _paragrafparent3
join rodzic_p in _paragrafparent3
on par.ParagrafParent equals rodzic_p.ParagrafID
orderby par.ParagrafParent, par.ParagrafID
select new ParagrafViewModel
{
ParagrafID = par.ParagrafID,
ParagrafNazwa = par.ParagrafNazwa,
ParagrafParent = par.ParagrafParent,
ParagrafCzynny = par.ParagrafCzynny,
ParagrafWplyw = par.ParagrafWplyw,
ParagrafParentNazwa = rodzic_p.ParagrafNazwa,
WniosekPodzialNazwa = par.WniosekPodzialNazwa
};
return View(paragrafModel);
}

Resources