extract the first three word in a string out - c#

I have the following codes:
void dbSvc_retrievepopularhawkerCompleted(object sender, RouteServiceRef.retrievepopularhawkerCompletedEventArgs e)
{
List<RouteServiceRef.Hawker> recommendPlaceList;
recommendPlaceList = e.Result.Cast<RouteServiceRef.Hawker>().ToList();
string hawkername = "";
string address = "";
string postal = "";
double coordX = 0.0;
double coordY = 0.0;
double popularity = 0;
foreach (RouteServiceRef.Hawker rp in recommendPlaceList)
{
hawkername = rp.hawkername;
address = rp.address;
postal = rp.postal;
coordX = rp.xcoord;
coordY = rp.ycoord;
popularity = rp.popularity;
cities.Add(new City() { Name = hawkername, Population = popularity });
}
ColumnSeries bs = ChartControl.Series[0] as ColumnSeries; bs.ItemsSource = cities;
}
How can I extract the first three word in the string of the hawkername ? The result for hawkername is:
I need to get the first three string out.

var firstThreeWords = hawkername.Split(' ').Take(3);
Don't forget to include using System.Linq; if you're not already using it:

Something like this will do :
var input = "ldsk bkfd badk klsfdl";
var result = string.Join(" ", input.Split(' ').Take(3));
Console.WriteLine(result);

Related

Implementing search in mvc 4

I have a textbox where user types the string he needs to search. If the user enters only a single word string, then I am able to retrieve the correct data from database but if the user enters a multi-word string then my code fails.
I am using EntityFramework to get the data.
Here is my code to get the data using a single word string.
public ActionResult SearchResult(string search)
{
var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(search) || oh.Description.Contains(search));
List<Mobiles> prod = new List<Mobiles>();
foreach (var p in j)
{
Mobiles Mob = new Mobiles();
Mob.Description = p.Description;
Mob.ImgUrl = p.Url;
Mob.MobileName = p.MobileName;
Mob.Price = Convert.ToString(p.Price);
Mob.SlNo = p.SlNo;
prod.Add(Mob);
}
return View("~/Views/Product/Index.cshtml", prod);
}
I tried breaking the string into single word using split but could not get the correct data.
string str = null;
string[] strArr = null;
int count = 0;
str = //UserInput;
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);
string str = null;
string[] strArr = null;
int count = 0;
str = search;
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);
for (count = 0; count <= strArr.Length - 1; count++)
{
string i = strArr[count];
var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(i) || oh.Description.Contains(i));
//MessageBox.Show(strArr[count]);
foreach (var p in j)
{
Mobiles Mob = new Mobiles();
Mob.Description = p.Description;
Mob.ImgUrl = p.Url;
Mob.MobileName = p.MobileName;
Mob.Price = Convert.ToString(p.Price);
Mob.SlNo = p.SlNo;
prod.Add(Mob);
}
}
as I help you fix the problem - this is the final code
I Wrote an Example to Solve your Problem. Hope That You will Be Benefited From The Code.
First Create Mobile Class:
public class Mobile
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Next Create Extension method To Check If there is Value:
public static bool ContainsAny(this string haystack, params string[] needles)
{
foreach (var needle in needles)
{
if (haystack.Contains(needle))
return true;
}
return false;
}
Finally Create Main Body Along with Test Data:
using System;
using System.Collections.Generic;
using System.Linq;
namespace StackOverFlow
{
static class Program
{
static void Main()
{
List<Mobile> mobiles = new List<Mobile>
{
new Mobile{Id = 1,Name = "samsung galaxy s3",Description = "model"},
new Mobile{Id = 2,Name = "nokia N67",Description = "nokia n96 time"},
new Mobile{Id = 3,Name = "iphone 5s",Description = "test"},
new Mobile{Id = 4,Name = "samsung galaxy packet",Description = "this time"},
new Mobile{Id = 5,Name = "iphone ipad",Description = "now"},
new Mobile{Id = 6,Name = "glx c5",Description = "time"},
};
string[] search = "galaxy time 5s".Split(' ');
var result = mobiles.Where(c => c.Name.ContainsAny(search) ||
c.Description.ContainsAny(search)).ToList();
foreach (var item in result)
{
Console.WriteLine(item.Id + "-" + item.Name + "-" + item.Description);
}
Console.ReadKey();
}

How can i ignore replace text within specific two symbol

I used following code snippet to replace text
private void textBox1_TextChanged(object sender, EventArgs e)
{
string A = textBox1.Text.Trim();
string B = textBox1.Text.Trim();
A = A.Replace("AB", "CD");
A = A.Replace("GF", "HI");
A = A.Replace("AC", "QW");
A = A.Replace("VB", "GG");
textBox2.Text = (A);
}
but i wants to ignore this replace technique within || these symbol.As a example my code do this
when i type AB GF in a txtbox1,txtbox2 replace as following CD HI.
Now i need when i type |AB GF| in txtbox1 ,txtbox2 replace as AB GF
i used this code to do this
textBox2.Text = ((B.Contains("|")) ? B.Replace("|", "") : A);
but this isn't work,after | this symbol all containing things in txtbox1 not replaced,how can i do this
Per your comments, you will want to split your string on the spaces prior to doing the replacement. Afterwards you will join it all back together. This is pretty easy with Linq.
public Main()
{
var strings = new string[]{ "AB GF", "|AB| GF" };
foreach (var s in strings)
Console.WriteLine(String.Join(" ", s.Split(' ').Select(x => ReplaceText(x))));
}
string ReplaceText(string text)
{
if (text.Contains("|"))
return text.Replace("|", String.Empty);
else
{
text = text.Replace("AB", "CD");
text = text.Replace("GF", "HI");
text = text.Replace("AC", "QW");
return text.Replace("VB", "GG");
}
}
Prints:
CD HI
AB HI
Looking at your code. If you need to avoid a ReplaceText method. Something like this would work.
string A = textBox1.Text.Trim();
var subStrings = A.Split(' ');
for (int i = 0; i < subStrings.Count(); i++)
{
if (subStrings[i].Contains("|"))
subStrings[i] = subStrings[i].Replace("|", String.Empty);
else
{
subStrings[i] = subStrings[i].Replace("AB", "CD");
subStrings[i] = subStrings[i].Replace("GF", "HI");
subStrings[i] = subStrings[i].Replace("AC", "QW");
subStrings[i] = subStrings[i].Replace("VB", "GG");
}
}
textBox2.Text = String.Join(" ", subStrings);

Dynamics NAV Webservice Fails on 2nd Loop

I have created a C# program to read a pipe ("|") delimited file and create purchase invoices and lines. Essentially, I have it loop through each line, if the "Report ID" has not been used, it creates a header, then the line, if the header has been created, it skips the header creation and is supposed to add the subsequent line. However, when I reach my object assignment for the line, it errors with:
"ArgumentException was unhandled"
"Must specify valid information for parsing the string."
The PIheader function works fine, so I have not included here. Please advise if more information/code is needed.
//Parse selected SAE File
SAEline[] sae = ParseSAE.Parse(file);
//Begin Analyzing Data
int saesize = sae.Length;
int i = 0;
List<string> cashIDs = new List<string>();
string paymentterms = "";
string invno = "";
string company = "";
string[] getcompany = new string[2];
string reportid = sae[i].ReportID;
int lineno = 0;
while(i < 10) //limit the loop for testing
//while (i < saesize)
{
if (sae[i].ReportEntryPaymentCodeCode != "CBCP")
{
if (!cashIDs.Contains(reportid))
{
cashIDs.Add(reportid);
getcompany = WebServices.GetCompany(sae[i].EmployeeID.ToUpper());
paymentterms = sae[i].ReportEntryPaymentCodeCode;
invno = WebServices.PIheader(getcompany[0], getcompany[1], 0, sae[i]);
lineno = 0;
}
lineno = lineno + 10000;
company = getcompany[0];
lineno = WebServices.PIlines(invno, lineno, company, sae[i]);
}
i++;
}
The WebService.cs contains:
//Web Service Client
PurchLines.PurchLines_PortClient piClient =
new PurchLines_PortClient((System.ServiceModel.Channels.Binding)basicHttpBindingNTLM,
new EndpointAddress("URL" + company + "/Page/PurchLines"));
//Conditional variables
string joblinetype = "";
string qty = "";
if (sae.ReportEntryCustom1 == "Billable")
{
joblinetype = "3";
}
if (sae.BusinessDistance == "")
{
if (sae.ReportCustom2 == "")
{
qty = "1";
}
else
{
qty = sae.ReportCustom2;
}
}
else
{
qty = sae.BusinessDistance;
}
string unitcost = (Convert.ToDecimal(sae.ReportEntryApprovedAmount)/Convert.ToDecimal(qty)).ToString();
//Line Creation
PurchLines.PurchLines line = new PurchLines.PurchLines()
{
No = sae.JournalAccountCode,
Line_No = Convert.ToInt16(lineno),
Line_NoSpecified = true,
Job_Line_TypeSpecified = true,
Job_Line_Type = (PurchLines.Job_Line_Type) (Enum.Parse(typeof (PurchLines.Job_Line_Type), joblinetype)),
QuantitySpecified = true,
Quantity = Convert.ToDecimal(qty),
TypeSpecified = true,
Type = (PurchLines.Type) (Enum.Parse(typeof (PurchLines.Type), "1")),
Direct_Unit_CostSpecified = true,
Direct_Unit_Cost = Convert.ToDecimal(unitcost),
Job_Unit_PriceSpecified = true,
Job_Unit_Price = Convert.ToDecimal(unitcost),
Job_No = sae.ReportEntryCustom5,
Job_Task_No = sae.ReportEntryCustom6,
Document_TypeSpecified = true,
Document_Type = (PurchLines.Document_Type)(Enum.Parse(typeof(PurchLines.Document_Type),"2")),
Document_No = invno
};
piClient.Create(ref line);
PurchLines.Create_Result result = new PurchLines.Create_Result(line);
int lin = result.PurchLines.Line_No;
return lin;
}
I realized that I didn't assign a value to joblinetype in the event that it is not "Billable", so the webservice was unable to Parse the blank string
Job_Line_Type = (PurchLines.Job_Line_Type) (Enum.Parse(typeof (PurchLines.Job_Line_Type), joblinetype)),

Select and pass datagridview row values to another form

In my application I want to select a full row in my datagridview and pass it to comboboxes which is located in another form. I tried it with following code but it is throwing me the error "No overload for method 'this' takes 1 arguments"
this is my code
if(dataGridView1.SelectedCells.Count > 0)
{
var oneCell = dataGridView1[0];
int editloannumber = int.Parse(dataGridView1.Rows[oneCell.RowIndex].Cells[0].Value.ToString());
int editlid = int.Parse(dataGridView1.Rows[oneCell.RowIndex].Cells[8].Value.ToString());
string editloantype = dataGridView1.Rows[oneCell.RowIndex].Cells[1].Value.ToString();
string editneworsecond = dataGridView1.Rows[oneCell.RowIndex].Cells[2].Value.ToString();
string editpurpose = dataGridView1.Rows[oneCell.RowIndex].Cells[11].Value.ToString();
string editstatus = dataGridView1.Rows[oneCell.RowIndex].Cells[3].Value.ToString();
string editcomments = dataGridView1.Rows[oneCell.RowIndex].Cells[7].Value.ToString();
string editretail = dataGridView1.Rows[oneCell.RowIndex].Cells[12].Value.ToString();
wartif_UW.editform e2 = new wartif_UW.editform(editloannumber, editloantype, editneworsecond, editpurpose, editstatus, editcomments, editretail,editlid);
e2.ShowDialog();
}
and this is my second form constructer
public editform(int editln, string edittype, string editno2, string purpo, string stat, string come,string reti,int lid)
{
InitializeComponent();
comboload();
loannumbertxtbox.Text = editln ;
loantypecombobox.Text = edittype;
loanpurposrcombo.Text = purpo;
neworseccombobox.Text = editno2;
retailregcombo.Text = reti;
statuscombbox.Text = stat;
commnetrichtext.Text = come;
}
DataGridView does not have an indexer. You had to do something like this:
if (dataGridView1.SelectedCells.Count > 0)
{
var oneCell = dataGridView1.SelectedCells[0];
int editloannumber = int.Parse(dataGridView1.Rows[oneCell.RowIndex].Cells[0].Value.ToString());
int editlid = int.Parse(dataGridView1.Rows[oneCell.RowIndex].Cells[8].Value.ToString());
string editloantype = dataGridView1.Rows[oneCell.RowIndex].Cells[1].Value.ToString();
string editneworsecond = dataGridView1.Rows[oneCell.RowIndex].Cells[2].Value.ToString();
string editpurpose = dataGridView1.Rows[oneCell.RowIndex].Cells[11].Value.ToString();
string editstatus = dataGridView1.Rows[oneCell.RowIndex].Cells[3].Value.ToString();
string editcomments = dataGridView1.Rows[oneCell.RowIndex].Cells[7].Value.ToString();
string editretail = dataGridView1.Rows[oneCell.RowIndex].Cells[12].Value.ToString();
wartif_UW.editform e2 = new wartif_UW.editform(editloannumber, editloantype, editneworsecond, editpurpose, editstatus, editcomments, editretail, editlid);
e2.ShowDialog();
}

adding items into list by for loops

I am creating a chart for windows phone 7.
This is the foreach for each hawker returned:
void dbSvc_retrievepopularhawkerCompleted(object sender, RouteServiceRef.retrievepopularhawkerCompletedEventArgs e)
{
List<RouteServiceRef.Hawker> recommendPlaceList;
recommendPlaceList = e.Result.Cast<RouteServiceRef.Hawker>().ToList();
string hawkername = "";
string address = "";
string postal = "";
double coordX = 0.0;
double coordY = 0.0;
double popularity = 0;
foreach (RouteServiceRef.Hawker rp in recommendPlaceList)
{
hawkername = rp.hawkername;
address = rp.address;
postal = rp.postal;
coordX = rp.xcoord;
coordY = rp.ycoord;
popularity = rp.popularity;
}
I have to change the above codes to be inside this list of cities:
List<City> cities = new List<City> { new City { Name = "CLE", Population = 2250871 }, new City { Name = "CMH", Population = 1773120 }, new City { Name = "CVG", Population = 2155137 }, new City { Name = "DET", Population = 4425110 } };
such as: List<City> cities = new List<City> { new City Name = hawkername, Population = popularity }
so that I can do a bind to my chart:
ColumnSeries bs = ChartControl.Series[0] as ColumnSeries; bs.ItemsSource = cities;
I am not sure how to mix them up, can someone guide me along ? As I do not want to hard code the name and population inside.
that's easy, Just follow the code below.
Declare the list of City Above the foreach loop and on each iteration just add new item to the list
List<City> cities = new List<City> ();
foreach (RouteServiceRef.Hawker rp in recommendPlaceList)
{
hawkername = rp.hawkername;
address = rp.address;
postal = rp.postal;
coordX = rp.xcoord;
coordY = rp.ycoord;
popularity = rp.popularity;
cities.Add(new City(){Name = hawkername, Population = popularity });
}
This fills the cities list as well on the completion of foreach loop.

Categories

Resources