Using ASCII equivalent in LINQ - c#

I have a list which want to order by the ASCII code of one field. What is the equivalent of an ASCII method in LINQ.
revisions = revisions.OrderBy(x => Ascii(x.SubRevision) % 90).ToList();
Method Ascii doesn't exist in LINQ. How I can use it?

It has nothing to do with LINQ really. If x.SubRevision is a char property you can simply cast it into an integer to get the ASCII value:
revisions = revisions.OrderBy(x => ((int)x.SubRevision) % 90).ToList();

There is, though. The function you need to use is System.Data.Objects.SqlClient.SqlFunctions.Ascii(x.Subrevision). This takes the leftmost character in x.Subrevision and gives the ASCII code for it.
However, this method can only be used in a LINQ to Entities query, not LINQ to SQL.
Like the others have answered, characters in C# can be casted to int for the same effect. So if x.Subrevision is a character you can simply cast it to int, if it's a string, you can cast the leftmost character to string, like this:
(int)x.Subrevision[0]

Related

Is sorting in LINQ by Ascii code?

In my LINQ to Entities query I have a .orderby f.Description.Trim() command
The reason for .Trim() is that some of the data coming from DB have a bunch of white spaces at the beginning of them so I wanted to trim those so they won't affect sorting.
Now it sorts correctly but I see something like this in the result:
[Queries - Blah]
Action
Adhere
Azalia
Then I looked up ASCII code of "[" and it is 91 and "A" is 65 so how come that one showed up first? Maybe there are some other things in the code causing this and sort is fine?
OrderBy is using the default comparator for strings, which doesn't use ASCII (actually, Unicode) ordinal comparison. It actually depends on the current culture you are using.
And, if you think about it... if you were sorting entries for an appendix or index, symbols come before letters (at least in English).
If you want to sort by "raw ascii value", use
...OrderBy(s => s, StringComparer.Ordinal)
If the actual expression can be compiled to a store expression, then the ordering will be done as implemented by your store.
So: the result will depend on the collation of the database, table and column.

Linq to Entity comparing strings ignores white spaces

When using LINQ to entity doing string comparisons will ignore white spaces.
In my table, I have an nchar(10) column so any data saved if it is not 10 characters will fill the rest with empty spaces. Below i am comparing the "ncharTextColumn" with the "Four" string. And even though the ncharText will equal "Four " It results in a match and the "result" variable will contain 1 record
TestEntities1 entity = new TestEntities1();
var result = entity.Table_1.Where(e => e.ncharText == "Four");
Is there an explanation for this and a way to work around it or am I going to have to call ToList on my query before any comparisons like so.
var newList = result.ToList().Where(e => e.ncharText == "Four");
This code now correctly returns 0 records as it takes into account white spaces. However, calling to list before a comparison can result in loading a large collection into memory which won't end up being used.
This answer explains why.
SQL Server follows the ANSI/ISO SQL-92 specification (Section 8.2, ,
General rules #3) on how to compare strings with spaces. The ANSI
standard requires padding for the character strings used in
comparisons so that their lengths match before comparing them. The
padding directly affects the semantics of WHERE and HAVING clause
predicates and other Transact-SQL string comparisons. For example,
Transact-SQL considers the strings 'abc' and 'abc ' to be equivalent
for most comparison operations.
The only exception to this rule is the LIKE predicate. When the right
side of a LIKE predicate expression features a value with a trailing
space, SQL Server does not pad the two values to the same length
before the comparison occurs. Because the purpose of the LIKE
predicate, by definition, is to facilitate pattern searches rather
than simple string equality tests, this does not violate the section
of the ANSI SQL-92 specification mentioned earlier.
Internally LINQ is just making SQL queries against your database.

How to cast a database entry to String

if((string)row["ProductID"].ToString() == txtBarcode.Text)
I want to search a row if the value of the txtbox is the same as my datatable but i have an error.. it says that Possible unintended reference comparison; to get a value comparison, cast the left hand side to string. i just use .ToString() and Convert.ToString() but still have that error.
Your .ToString() is converting the row value to a string, so you don't also need to cast it on the left with (string)
Ie. if(row["ProductID"].ToString() == txtBarcode.Text)
Personally, I'd stare clear of using == operator with anything but ints, chars and whether this instance is that instance.
A better way of comparing strings is to use string.Equals(string) string.contains(string) or string.indexOf(string)
Note : if you are comparing with TextBox value then it is better to trim the values before comparing to remove the whitespaces using Trim() method.
Solution 1: if you want to find the excat match then you need to use Equals() method.
if(row["ProductID"].ToString().Equals(txtBarcode.Text.Trim())
{
/* do something*/
}
Solution 2: if you want to find the part of the string then you can use String.Contains() method as below:
if(row["ProductID"].ToString().Contains(txtBarcode.Text.Trim())
{
/* do something*/
}
You need to do one of the above. Either do a cast (string)row["ProductId"] or Convert.ToString(row["ProductId"]) for converting the value to string. But casting using (string)row["ProductId"] is likely to throw InvalidCastException. So may be ToString() would be better.

Specified Cast is not Valid - trying to cast a char

I am trying to cast a char as follows:
while (Reader.Read())
{
VM VMResult = new VM();
VMResult.status = (char)Reader["status"];
VMList.Add(VMResult);
}
Then comes the fun part: Specified Cast is not Valid.
VMResult.status is a char
The returned data is a char(1) in sql
I assume there must be a difference in the C# / SQL char terminology.
What do you think?
I assume there must be a difference in the C# / SQL char terminology.
That's correct. A char in sql server is a fixed length character string. It can be nullable.
A char in .net is a structure that represents a single character as a UTF-16 code unit. It cannot be null since its a structure
There is no fixed length character string .Net unless you consider a char array or byte array a fixed length string.
Since most of the .net ecosystem has better support for strings than chars, char arrays or byte arrays, you're much better off just using the string that gets returned for the char(x) fields.
If you know for a fact that Reader["status"] will always be a char (or you only want the first char), and the current type of Reader["status"] is a string you can always
VMResult.status = (!string.IsNullOrEmpty(Reader["status"])) ?
Reader["status"].ToCharArray()[0] : '';
EDIT: null checking ftw.
OK so you basically want to cast a string to a char, this is going to assume that your "status" value is a single character string:
VMResult.status = Reader["status"].ToString()[0];
this also assumes Reader[] does not already return a string (if it did then the ToString is not required) and that the value is not null.

Error when using .Contains to check if a string contains a character

I am trying to find out if a string contains a character. I tried the following
where ViewBag.Options is a string:
#ViewBag.Options.Contains('q')
but it gives me an error saying:
The best overloaded method match for 'string.Contains(string)' has some invalid arguments.
And it's write: string.Contains doesn't have an overload taking just a single character.
Options:
Use #ViewBag.Options.Contains("q")
Use #ViewBag.Options.IndexOf('q') != -1
Use some more complicated LINQy approach (e.g. Any) - feasible, but there's no need here. (I'm a fan of LINQ where appropriate but I don't think that's the right approach here; I wouldn't start introducing lambda expressions into my code just for the sake of it)
Use some more complicated regular expression approach - again, there's no point.
Using single quotes in c# indicates a character.
Try with double quotes:
#ViewBag.Options.Contains("q");
Use this:
#ViewBag.Options.Contains("q")
Use any of them
#ViewBag.Options.Contains("q");
#ViewBag.Options.Any(x => x == 'q');
If you insist
#ViewBag.Options.Contains('q'.ToString());
The error is self explanatory. Paramerters of .Contains takes a string and no overload of this method takes a character.

Categories

Resources