How to set prefix in string in join? - c#

I have this strings:
string[] codes = new string[]{"66000110", "66000001", "66000121"};
I want to make join on strings above:
string filter = string.Join(" OR " + some_ID + "=", codes );
The resukt I get is:
some_ID=66000110 OR some_ID=66000001 OR some_ID=66000121
While I need the string like that(OR missing on start string):
OR some_ID=66000110 OR some_ID=66000001 OR some_ID=66000121
How do I fix elegantic way to get OR on start of the string?

It seems that you are building some kind of SQL; if it's your case, try switching to IN:
string filter = $" OR {some_ID} IN ({string.Join(", ", codes)})";
And you'll get a more readable equivalent
" OR some_ID IN (66000110, 66000001, 66000121)"

You can use a combination of LINQ and Concat():
string filter = string.Concat(codes.Select(c => " OR " + some_ID + "=" + c));

Why not something like this?
string filter = " or " + string.Join(" OR " + some_ID + "=", codes );

Related

Replace char in string not working

I am trying to replace a hash char in a string but the following is not working the
string address = "Blk 344, Jurong West, Street 11, #02-111";
address.Replace("#","%23");
Any ideas guys been driving me crazy
Query String full
http://localhost:54965/SKATEZ/thankyou.aspx?firstname=Fiora&lastname=Ray&address=Blk%20344,%20Jurong%20West,%20Street%2011,%20#02-111&total=22&nirc=S6799954H&country=Singapore&orderid=85&postalcode=746112
I construct the url as follows
string url = "thankyou.aspx?firstname=" + firstname + "&" + "lastname=" + lastname + "&" + "address=" + HttpUtility.EscapeDataString(address) + "&" + "total=" + total + "&" + "nirc=" + tbID.Text + "&" + "country=" + ddlCountry.SelectedValue + "&" + "orderid=" + orderid + "&" + "postalcode=" + tbPostalCode.Text;
Response.Redirect(url);
Try
address = address.Replace("#","%23");
Strings in C# are immutable:
Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.
Using System.Uri.EscapeDataString(string) should fix your issue:
var urlbuilder = new StringBuilder();
urlbuilder.AppendFormat("thankyou.aspx?firstname={0}", firstname);
urlbuilder.AppendFormat("&lastname={0}", lastname);
urlbuilder.AppendFormat("&address={0}", System.Uri.EscapeDataString(address));
urlbuilder.AppendFormat("&total={0}", total);
urlbuilder.AppendFormat("&nirc={0}", tbID.Text);
urlbuilder.AppendFormat("&country={0}", ddlCountry.SelectedValue);
urlbuilder.AppendFormat("&orderid={0}", orderid);
urlbuilder.AppendFormat("&postalcode={0}", tbPostalCode.Text);
Response.Redirect(urlbuilder.ToString());
(using System.Text.StringBuilder to compose your url makes the code a little more readable)

What is the replacement Sql Char(13) and isnull in Entity Framework?

I am new to Entity framework, Can any body tell me how to write the following query into Entity framework.
select column1 + char(13) +isnull(column2,space(1))+char(13)+isnull(column3,space(1))+char(13)+isnull(column4,space(1)) +char(13)+isnull(olumn5,space(1)) as FADRS
FROM table
Convert the above query into Entity Framework.
By using Jon answer i get the answer. Know my problem is how to use iqueryable
IQuer<string> Madr = from b in context.table
where b.column1 == txtaddrss.Text
select new
{FADR = b.column2 + '\r' +
(b.column3 ?? " ") + '\r' +
(b.column4 ?? " ") + '\r' +
(b.column5 ?? " ") + '\r' +
(b.column6 ?? " ")};
foreach(string something in Madr)
{
MessageBox.Show(something);
}
i am getting error conversion failed because of anonymous type
char(13) just does the equivalent (though more limited) of (char)13 in C#, which would just return '\r'.
Hence you would either use '\r' or "\r".
isnull(x, y)just does the equivalent of x ?? y in C#.
So you would use something like:
var query = from item in TableSource select
item.column1 + '\r' +
(item.column2 ?? " ") + '\r' +
(item.column3 ?? " ") + '\r' +
(item.column4 ?? " ") + '\r' +
(item.column5 ?? " ");
TableSource is whatever way you are getting a reference to the table (context.Table or whatever).
query will be an IQueryable<string> returning the relevant strings when invoked. If you really want the FADRS name from your example then the following will instead of strings return anonymous objects with a FADRS property:
var query = from item in TableSource select
new {FADRS = item.column1 + '\r' +
(item.column2 ?? " ") + '\r' +
(item.column3 ?? " ") + '\r' +
(item.column4 ?? " ") + '\r' +
(item.column5 ?? " ")};
Edit:
The first example above can be used as:
foreach(string something in query)
MessageBox.Show(something);
The second example as:
foreach(var something in query)
MessageBox.Show(something.FADR);
With the first var is optional shorthand, with the second you must use var as the types involved are anonymous, and hence var is the only way to name the type (by not naming it at all).
Given no further context I'd say sonething like this:
var query = from obj in context.table
select new {
FADR = obj.column1 + "\r" +
obj.column2 ?? " " + "\r" +
obj.column3 ?? " " + "\r" +
obj.column4 ?? " " + "\r" +
obj.column5 ?? " " + "\r" };

Concatenating IEnumerable<KeyValuePair<string,string>> values into string using Linq

Given IEnumerable<KeyValuePair<string,string>>, I'm trying to use linq to concatenate the values into one string.
My Attempt:
string path = attributes.Aggregate((current, next) => "#" + current.Key + "=" + current.Value + " and #" + next.Key + "=" + next.Value);
This produces the error:
Cannot convert expression type 'string' to return type 'KeyValuePair<string,string>'
Is there a more effiecient way to do this in linq?
The full method...
public IEnumerable<XmlNode> GetNodes(IEnumerable<KeyValuePair<string,string>> attributes) {
StateInfoXmlDocument stateInfoXmlDocument = new StateInfoXmlDocument();
string path = attributes.Aggregate((current, next) => "#" + current.Key + "=" + current.Value + " and #" + next.Key + "=" + next.Value);
string schoolTypeXmlPath = string.Format(SCHOOL_TYPE_XML_PATH, path);
return stateInfoXmlDocument.SelectNodes(schoolTypeXmlPath).Cast<XmlNode>().Distinct();
}
Is this what you're looking for?
var strings = attributes.Select(kvp => string.Format("#{0}={1}", kvp.Key, kvp.Value));
string path = string.Join(" and ", strings);
string s = String.Join("#",attributes.Select(kv=>kv.Key+"="+kv.Value));
If you want to use aggregate to make a string you need to use the seeded overload of aggregate
if you use the none seeded version then all the types in the call need to be the same.
string templ = "{0}={1}";
string _authStr = String.Join("&", formParams.Select(kv => String.Format(templ, kv.Key, kv.Value));

How to remove special characters with regex instead of Replace string

My current method:
var q = new StringBuilder(query);
return q.Replace("'", " ")
.Replace("\"", " ")
.Replace(":", "")
.Replace("#", " ")
.Replace("/", " ")
.Replace("\\", " ")
.Replace(",", " ")
.Replace("&", " ")
.Replace("?", " ")
.Replace("%", " ")
.Replace(".", " ")
.Replace("quot;", " ")
.Replace("-", " ")
.Replace("*", " ")
.ToString().Trim();
How can I done this using regex for better performance?
Edited: Sorry, I want replace all special characters by space " ".
You could use this:
string q = Regex.Replace(query, #"[:#/\\]", ".");
q = Regex.Replace(q, #""|['"",&?%\.*-]", " ");
EDIT:
On closer inspection of what you're doing, your code is translating several characters into ., and then translating all . into spaces. So you could just do this:
string q = Regex.Replace(query, #""|['"",&?%\.*:#/\\-]", " ").Trim();
I'm not really sure what you're trying to do here, though. I feel like what you're really looking for is something like:
string q = Regex.Replace(query, #"[^\w\s]", "");
The presence of " in there throws me for a loop, and is why I'm not sure what you're doing. If you want to get rid of HTML entities, you could run query through HttpUtility.HtmlDecode(string) first and then apply the regex.
Try this.
string pattern = #"[^a-zA-Z0-9]";
string test = Regex.Replace("abc*&34567*opdldld(aododod';", pattern, " ");

LINQ query Concat values to list of type string

Is there a more efficient way to handle this?
List<String> lstReferences = (from f in
(from section in courseSectionToCreate.SectionsToAdd
select new {
ReferenceNumber = section.Course.CourseNumber.Substring(0, 5) + "." +
section.Course.CourseNumber.Substring(5) + "." +
section.Session + "." +
section.Year + "." +
section.SectionNumber + ";"
})
select f.ReferenceNumber).ToList();
strReferenceNumber = lstReferences.Aggregate((a, b) => a + ", " + b);
Yes, you definitely don't want to be using Aggregate here. That is O(n^2) (it's Schlemiel the Painter's algorithm). Instead:
string referenceNumber = String.Join(", ", lstReferences);
This is better because String.Join will use a StringBuilder internally.
You can replace all that with this:
var strReferenceNumber =
String.Join(", ",
courseSectionToCreate.SectionsToAdd.Select(s =>
String.Join(".",
s.Course.CourseNumber.Substring(0, 5),
s.Course.CourseNumber.Substring(5),
s.Session,
s.Year,
s.SectionNumber) + ";"
)
);
How about:
var lstReferences = from section in courseSectionToCreate.SectionsToAdd
let courseNumber = section.Course.CourseNumber
let toJoin = new object[]
{
courseNumber.Substring(0, 5),
courseNumber.Substring(5),
section.Session,
section.Year,
section.SectionNumber
}
select string.Join(".", toJoin) + ";"
var strReferenceNumber = string.Join(", ", lstReferences);

Categories

Resources