So I am currently working on a calculator.
One of the requirements is to store the history, which I currently do in a list.
While I have simplified alot of code I can't get my head around simplifying this
if (amountNumbers == 2)
{
memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " = " + calculation.ToString());
userNumbers.Clear();
}
if (amountNumbers == 3)
{
memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " " + op + " " + userNumbers[2].ToString() + " = " + calculation.ToString());
userNumbers.Clear();
}
if (amountNumbers == 4)
{
memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " " + op + " " + userNumbers[2].ToString() + " " + op + " " + userNumbers[3].ToString() + " = " + calculation.ToString());
userNumbers.Clear();
}
if (amountNumbers == 5)
{
memory.Add(userNumbers[0].ToString() + " " + op + " " + userNumbers[1].ToString() + " " + op + " " + userNumbers[2].ToString() + " " + op + " " + userNumbers[3].ToString() + " " + op + " " + userNumbers[4].ToString() + " = " + calculation.ToString());
userNumbers.Clear();
}
Any idea how I simplify this and make the adding dynamic depending on how many values the user has chosen?
Preferably I want to store the whole string within one index since that is how the history is being displayed.
You can just Join userNumbers values with " " + op + " " separator, then concat calculation at end:
string lastExpression = string.Join(" " + op + " ", userNumbers) + // Join values
" = " + calculation.ToString(); // Concat calculation result
memory.Add(lastExpression);
userNumbers.Clear();
There is no matter which amount of values in userNumbers - they all will be joined with " " + op + " " between each other.
Shorter version with string interpolation:
memory.Add($"{string.Join($" {op} ", userNumbers)} = {calculation}");
userNumbers.Clear();
EDIT.
This is very similar idea with #JonasH's answer, just without converting userNumbers to a collection of strings. Join makes it implicitly at behind.
Easy, loop over userNumbers and build your string, then add it to memory once you're done. Like so:
// Ensure that we don't get an 'IndexOutOfBoundsException'
// By clamping 'amountNumbers' to the length if 'userNumbers' if it's larger
if (amountNumbers > userNumbers.Length)
amountNumbers = userNumbers.Length;
// You could use a normal 'string' and '... += ...' but 'StringBuilder' is more efficient
var sb = new StringBuilder();
for (int i = 0; i < amountNumbers; i++)
sb.Append($"{userNumbers[i].ToString()} ");
// Add the calculation, no space at the start required as the loop adds a trailing space
sb.Append($"= {calculation.ToString()}");
memory.Add(sb.ToString());
Use .Take(amountNumbers) to get at most amountNumbers of user numbers, . And String.Join to combine strings with some separator between each:
var users = userNumbers.Take(amountNumbers).Select(s => s.ToString());
var str = string.Join(" " + op + " ", users);
memory.Add(str + " = " + calculation.ToString());
If you need some special handling for cases, like if amountNumbers< userNumbers.Count or amountNumbers == 1 you need to add that separately. If you know that amountNumbers == userNumbers.Count, then the .Take(...) is not needed.
Related
I've been having extreme difficulty with figuring out how to either make a new line of text in the same comment and how to make them line up with each other on the left "wall" of the comment. Maybe the answer is obvious and I just need another set of eyes.
public async void PrintInfo()
{
string info =
"**Stats:**" + "".PadRight(93) +
behindWholeStat[0] + " = " + wholeStats[0] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[0]) + 1)))
+ behindWholeStat[1] + " = " + wholeStats[1] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[1]) + 1)))
+ behindWholeStat[2] + " = " + wholeStats[2] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[2]) + 1)))
+ behindWholeStat[3] + " = " + wholeStats[3] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[3]) + 1)))
+ behindWholeStat[4] + " = " + wholeStats[4] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[4]) + 1)))
+ behindWholeStat[5] + " = " + wholeStats[5] + "".PadRight((int)(90 - Math.Floor(Math.Log10(wholeStats[5]) + 1)))
+ "**Race:** " + rasr.chossenRace + ", **Subrace:** " + rasr.chossenSubrace + "".PadRight(83 - (rasr.chossenRace.Length + rasr.chossenSubrace.Length))
+ "**Class:** " + casc.chossenClass + ", **Subclass:** " + casc.chossenSubclass + "".PadRight(81 - (casc.chossenClass.Length + casc.chossenSubclass.Length))
+ "**Alignment:** " + chossenAlignment + "".PadRight(85 - (chossenAlignment.Length));
await ReplyAsync(info);
}
Im not quite sure but I think what you are looking for is "\n"
You can insert line breaks in a string with \n
"This will be in first line\nThis will be in second line\nAnd this will be in third"
Output:
This will be in first line
This will be in second line
And this will be in third
Hello i have a long SQL Query for Oracle DB. My Problem is i'm searching for arround 2 hours to get the error fixed. On all Queries i have the same error with parenthesis.
Here is my class where i get the error inside the command of OracleDB Query. I didnt find the error. The Query shown below is working on Delphi without problems. The only thing i change are the quotation marks at the beginning and at the end of each line which a normally single quoted.
using System;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;
namespace RawBinderLabel
{
public partial class Rawbinder_Manually : Form
{
private database_conn db_conn = new database_conn();
private OracleConnection OraConn = new OracleConnection();
public Rawbinder_Manually()
{
InitializeComponent();
get_rawbinder_data();
}
public void get_rawbinder_data()
{
string rcs = db_conn.connection();
using (OracleConnection OraConn = new OracleConnection(rcs))
{
using (OracleCommand OraCmd = OraConn.CreateCommand())
{
try
{
OraConn.Open();
OraCmd.BindByName = true;
//SQL Command to retrieve manual binder that ar OK
OraCmd.CommandText = "SELECT l.a_layer_pos, " +
" l.a_serial, " +
" P_ROHBINDER_ETIKETTEN.GET_BARCODE (mb.a_serial,''M'') Barcode, " +
" mb.a_splitted," +
" mb.a_dlam, " +
" l.a_order_id, " +
" l.a_section_id, " +
" P_ROHBINDER_ETIKETTEN.GET_MANUALPOSITIONS (mb.a_serial) Positionen, " +
" P_ROHBINDER_ETIKETTEN.GET_MANUALABBUND (mb.a_serial) abbund, " +
" P_ROHBINDER_ETIKETTEN.GET_MANUALQUALITY (mb.a_prodquality_id) qualitaet, " +
" to_char(lt.LIEFERTERMIN, ''dd.mm.yyyy'') liefertermin, " +
" ''1'' a_beam_pos, " +
" P_ROHBINDER_ETIKETTEN.GET_MAXMANUALLENGTH (l.a_serial) max_a_length, " +
" substr(c.a_cust_name,1,40) kunde, " +
" l.a_dimter_start_date, " +
" l.a_dimter_end_date, " +
" p.a_prod_date, " +
" p.a_destheight, " +
" p.a_description, " +
" dl.a_layer_serial, " +
" dl.a_width, " +
" dl.a_lamellaheight, " +
" dl.A_RAWWIDTH, " +
" dl.A_RAWLAMELLAHEIGHT, " +
" dl.A_GLUE_DESCRIPTION, " +
" dl.A_COLOR_DESCRIPTION, " +
" dl.a_pressproc_description, " +
" dl.a_pressproc_description ||' - ' || p.a_description || '' - ('' ||p.a_destlength || '')'' pressbett, " +
" mb.a_serial beam_serial," +
" mb.a_prodquality_id," +
" FROM t_manual_layer l," +
"t_manual_pressproc p, " +
"t_dimter_layer dl, " +
"t_manualbeam mb, " +
"v_liefertermin lt, " +
"t_order o, " +
"t_customer c " +
" WHERE to_char(p.a_prod_date,''DD.MM.YYYY'') = ''' :rawbinder_date '''" +
" and p.a_pressproc_id = l.a_pressproc_id " +
" AND l.A_SERIAL = dl.A_SERIAL " +
" AND mb.A_LAYER_SERIAL = l.a_serial " +
" AND lt.PROJEKTNR = l.a_order_id " +
" AND lt.GPID = l.a_section_id " +
" AND o.a_order_id = l.a_order_id " +
" and c.a_customer_id = o.a_customer_id " +
" order by l.A_SERIAL, l.a_layer_pos";
//Assign Parameters to Date selected in Overview Form
OracleParameter rawbinder_date = new OracleParameter("rawbinder_date", RawBinder_Overview.rawbinder_date);
OraCmd.Parameters.Add(rawbinder_date);
//Execute the command and display it using DataReader
OracleDataReader OraDataRead = OraCmd.ExecuteReader();
while (OraDataRead.Read())
{
Console.WriteLine("Manually Implemented" + OraDataRead.GetString(0));
}
}
catch (OracleException ex)
{
switch (ex.Number)
{
case 1:
MessageBox.Show("Fehler beim Einfügen der Daten");
break;
case 12560:
MessageBox.Show("Die Datenbank ist nicht erreichbar.");
break;
default:
MessageBox.Show("Datenbankfehler: " + ex.Message.ToString());
break;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
OraConn.Dispose();
}
}
}
}
}
}
Does someone has an Idea how to fix that Problem?
I think there are multiple issues:
2 times single quotes are not required everywhere
comma after " mb.a_prodquality_id," + is not required as it is the last expression of SELECT clause
as mentioned in the comment by #crowcoder, single quotes around parameters are not required. Means around this: :rawbinder_date
Try to solve all this problems and check if it executes properly.
I am getting the following error trying to query from my database using C#:
LINQ to Entities does not recognize the method 'MyProject.Models.DB.Department getDepartment()' method, and this method cannot be translated into a store expression.
In my controller I have:
var query = db.Activities.AsQueryable();
query = query.Where(x => rs.department.Contains(x.getDepartment().id));
In my model I have the following method which returns the correct Department for an Activity. I know the problem is that I am executing the query when I do the .First(), but I can't find a way to return this as a IQueryable result:
public partial class Activity
{
public Department getDepartment()
{
return db.Departments.SqlQuery( "" +
"SELECT * FROM " +
"[snt].[Departments] " +
"INNER JOIN( " +
"SELECT " +
"[Users].departments_id AS id " +
"FROM " +
"[snt].[Users], " +
"[snt].[People], " +
"[snt].[EventPerson], " +
"[snt].[EventPersonTask], " +
"[snt].[Tasks], " +
"[snt].[Events], " +
"[snt].[Activities] " +
"WHERE " +
"[snt].[Activities].id = {0} AND " +
"[snt].[Events].id = [snt].[Activities].events_id AND " +
"[snt].[EventPerson].events_id = [snt].[Events].id AND " +
"[snt].[EventPerson].people_id = [snt].[People].id AND " +
"[snt].[EventPersonTask].tasks_id = [snt].[Tasks].id AND " +
"[snt].[EventPersonTask].eventperson_id = [snt].[EventPerson].id AND " +
"[snt].[Tasks].name = 'owner' AND " +
"[snt].[Users].is_active = 1 AND " +
"[snt].[Users].people_id = [snt].[People].id" +
" ) AS x " +
"ON " +
"x.id = [Departments].id", this.id).First();
}
}
Using CsvHelper with .NET Core 2.2.
We're parsing a CSV file to then export to a SQL table. There are two different mappings of the CSV columns to the SQL columns, which depend on the first value of each row of the CSV.
This is what we have:
public List<TaskProdEntity> ParseCSVFile()
{
using (var reader = new StreamReader(#"C:\Users\me\Desktop\pfile.csv"))
using (var csv = new CsvReader(reader))
{
csv.Configuration.PrepareHeaderForMatch = (string header, int index) =>
header.Replace(" ", "_").Replace("(", "").Replace(")", "").Replace(".", "");
List<TaskProdEntity> records = new List<TaskProdEntity>();
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
if (csv.GetField<int>(0) == 1)
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id"),
Region = "Business Mailing Address:" + " " + csv.GetField<string>("Provider_First_Line_Business_Mailing_Address") + " " + csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_City_Name") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_State_Name") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Postal_Code") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Country_Code_If_outside_US") + " | " + "Business Practice Location:" + " " + csv.GetField<string>("Provider_First_Line_Business_Practice_Location_Address") + " " + csv.GetField<string>("Provider_Second_Line_Business_Practice_Location_Address") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_City_Name") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_State_Name") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Postal_Code") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Country_Code_If_outside_US"),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_1")
};
records.Add(record);
}
else
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id3"),
Region = "Business Mailing Address:" + " " + csv.GetField<string>("Provider_First_Line_Business_Mailing_Address2") + " " + csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_City_Name2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_State_Name2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Postal_Code2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Country_Code_If_outside_US2") + " | " + "Business Practice Location:" + " " + csv.GetField<string>("Provider_First_Line_Business_Practice_Location_Address2") + " " + csv.GetField<string>("Provider_Second_Line_Business_Practice_Location_Address2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_City_Name2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_State_Name2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Postal_Code2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Country_Code_If_outside_US2"),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_2")
};
records.Add(record);
}
}
return records;
}
}
Because the mapping for the Region field specifically is so messy and long, I really want to extract values from those csv fields only if the field is not blank. In many cases, many of those fields will be blank, and the business does not want a ton of concatenated blanks to end up in the database in these cases.
I am wondering if CsvHelper already has a built-in function to achieve this? If not, how would I implement that logic into the above code?
Since the second TaskProdEntity appears to add a 2 each time to the column header, you could have one method that builds your address.
public List<TaskProdEntity> ParseCSVFile()
{
using (var reader = new StreamReader(#"C:\Users\me\Desktop\pfile.csv"))
using (var csv = new CsvReader(reader))
{
csv.Configuration.PrepareHeaderForMatch = (string header, int index) =>
header.Replace(" ", "_").Replace("(", "").Replace(")", "").Replace(".", "");
List<TaskProdEntity> records = new List<TaskProdEntity>();
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
if (csv.GetField<int>(0) == 1)
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id"),
Region = GetAddress(csv),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_1")
};
records.Add(record);
}
else
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id3"),
Region = GetAddress(csv, "2"),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_2")
};
records.Add(record);
}
}
return records;
}
}
private string GetAddress(CsvReader csv, string extension = "")
{
var value = new StringBuilder("Business Mailing Address:");
if (csv.GetField<string>("Provider_First_Line_Business_Mailing_Address" + extension) != string.Empty)
{
value.Append(" " + csv.GetField<string>("Provider_First_Line_Business_Mailing_Address" + extension));
}
if (csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address" + extension) != string.Empty)
{
value.Append(" " + csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address" + extension));
}
// The rest of the if statements..............
return value.ToString();
}
I want each Total displayed on a different line in the box but at the moment it keep overlapping.
Could someone please show me the way?
private void SummaryButton_Click(object sender, EventArgs e)
{
TotalMoniesTaken = AmountDue + TotalMoniesTaken;
TotalGuests = NumberOfGuests + TotalGuests;
TotalLunchBookings = NumberOfGuests + TotalLunchBookings;
TotalEarlyBookings = NumberOfGuests + TotalEarlyBookings;
TotalLateBookings = NumberOfGuests + TotalLateBookings;
TotalCornerTables = NumberOfGuests + TotalCornerTables;
TotalWaiters = NumberOfGuests + TotalWaiters;
MessageBox.Show("Total Monies Taken is €" + TotalMoniesTaken +
"Total Number of Bookings = " + TotalGuests +
"Total Lunch Bookings = " + TotalLunchBookings +
"Total Early Bookings = " + TotalEarlyBookings +
"Total Late Bookings = " + TotalLateBookings +
"Total Corner Tables = " + TotalCornerTables +
"Total Waiters = " + TotalWaiters);
}
Displaying this doesn't include a new line:
"Total Monies Taken is €" + TotalMoniesTaken
But this does:
"Total Monies Taken is €" + TotalMoniesTaken + Environment.NewLine
Add newlines to each one :
"Total Monies Taken is €" + TotalMoniesTaken + Environment.NewLine
"Total Number of Bookings = " + TotalGuests + Environment.NewLine
..etc
There are a few ways that you can do this in C#, firstly you can use newlines in your string
MessageBox.Show("Total Monies Taken is €" + TotalMoniesTaken +
"\nTotal Number of Bookings = " + TotalGuests +
"\nTotal Lunch Bookings = " + TotalLunchBookings +
"\nTotal Early Bookings = " + TotalEarlyBookings +
"\nTotal Late Bookings = " + TotalLateBookings +
"\nTotal Corner Tables = " + TotalCornerTables +
"\nTotal Waiters = " + TotalWaiters);
Alternatively, you could use Environment.NewLine
MessageBox.Show("Total Monies Taken is €" + TotalMoniesTaken + Environment.NewLine +
"Total Number of Bookings = " + TotalGuests + Environment.NewLine +
"Total Lunch Bookings = " + TotalLunchBookings + Environment.NewLine +
"Total Early Bookings = " + TotalEarlyBookings + Environment.NewLine +
"Total Late Bookings = " + TotalLateBookings + Environment.NewLine +
"Total Corner Tables = " + TotalCornerTables + Environment.NewLine +
"Total Waiters = " + TotalWaiters);
just use \n at the end of each line
MessageBox.Show("test1 \n test2 \n test3");
You can do two ways:
1st one with \n:
Eg: string msg = "text\nwith two lines";
2nd way with Environment.NewLine:
Eg:string msg = "Text " + Environment.NewLine + "with two lines";
Some of the newer C# features (not tested)
MessageBox.Show(
$#"Total Monies Taken is €{TotalMoniesTaken}
Total Number of Bookings = {TotalGuests}
...");