Linq C# to Vb .Net - c#

Im struggling trying to convert this code. As well as googling for an answer and reading MSDN documentation i still cant figure this out. Ive also looked at the examples
101 for Visual Basic .Net
101 for C# .Net
Hers some C# code im trying to convert:
var asciiCredentials = (from c in credentials
select c <= 0x7f ? (byte)c : (byte)'?').ToArray();
My attempt so far:
Dim ascii = (From c In Credentials(Function(x) x= 0x7f .....)
But cant figure it out!! I think the Byte conversion is putting me off track.
Can anyone advise

Remember that Visual Basic has the IIf command that, in some respects, acts like the ternary operator.
Dim ascii = (From ch In s
Select IIf(Char.GetNumericValue(ch) < 127, Convert.ToByte(ch), Convert.ToByte("?"c))).ToArray()

You can use If in place of the conditional operator, making the code:
Dim asciiCredentials = credentials.Select(Function(x) _
If(x <= 127, Convert.ToByte(c), Convert.ToByte("?"C)))_
.ToArray();

Dim asciiCredentials = (
From c In credentials
Select If(c <= &H7f, CByte(c), AscW("?"c))).ToArray()

Dim asciiCredentials = (From c In credentials Select If(c <= &H7f, CByte(c), CByte(AscW("?"C)))).ToArray()
Taken from here:http://www.developerfusion.com/tools/convert/csharp-to-vb
They usually do pretty well converting.

Related

Why in Excel comparing 1<' or comparing any number to any text with < results in true?

In Excel 1234 > qwer = false, but 1234 < qwer = true. Having worked with nullable types in C# I would expect both statements to return false like when comparing values to nulls.
What is rationale behind that? Is it documented somewhere?
My first thought was that Excel internally converts numbers to strings and then compares strings, but then:
'129 < '11a = false - when left part is entered as text
129 < '11a = true - when left part is entered as a number
In VBA variant type comparison works the same way as on spreadsheets
Sub CompareNumberAndText()
Dim a, b, c
at = "129"
an = 129
b = "11a"
ct = at < b 'false
cn = an < b 'true
End Sub
I am developing a library with a type similar to Excel cell and wanted to make behavior as close to Excel as possible, but these Excel comparison results are counter-intuitive. I would throw an error or return false in this case.
I could imagine a hypothetical situation when in column A I calculate some value by dividing two numbers, e.g. P/E ratio, but for negative E I put "n.m.". Then in column B I check if P/E > some_value, I will get true for n.a. If the exercise is to find expensive stocks, then showing ones with negative earnings makes some (but very little) sense and could be useful for further manual one-by-one analysis when there are 20 stocks. But if there are 2000 ones and I calculate some aggregates, this could go unnoticed.
You can refer to Comparing Strings by Using Comparison Operators
According to this for your string comparison at < b, the ASCII value of first character 1 is 49 and same for at and b, however the for the second character the ASCII value of 2 is more than the ASCII value of 1, hence the expression at < b return false
Also as explained in greater detail in Comparison Operators (Visual Basic), if you defined the primitive types of the variables the behavior get changed, see below
Case-1:
Sub CompareNumberAndText()
Dim at As String, b As String, c As String, an As Integer
at = "120"
an = 2
b = "1"
c = "3"
ct = at < b 'false
cn = an < b 'false
kl = an < c 'true
End Sub
Case-2:
Sub CompareNumberAndText()
Dim at As String, b As String, an As Integer
at = "120"
an = 2
b = "1a"
ct = at < b 'false
cn = an < b 'error
End Sub
In Case-1 above the string b and c are converted to double and then compared to the value of an and results in proper boolean values as a result, however in Case-2 the program fails to convert the variable b to a double value and throws an error Run Time Error - 13, Type Mismatch.
Duplicating the way Excel treats comparisons is not a trivial exercise - you need to investigate Unicode collating sequences and locales. For some discussion of the problems see this blog post on sorting and comparing the Excel way

C# ?: Expression

I have a function with multiple if's (THIS IS NOT THE ACTUAL CODE)
if(n == 1)
m = 1;
if(n == 2)
m = 2;
if(n == 3)
m = 3;
Instead of that I wanted to do make them all into ?: expression :
(n == 1) ? m = 1;
But it says that its expecting a ':'
I am familiar with the ?: expression from C++ where you can simply write:
(n == 1) ? m = 1 : 0;
But 0 doesn't take here. This is a ridiculous question and I couldn't even find an answer in google since it ignores '?:' as a word.
ANSWER : too bad the answer was in the comments. There is no way to "do nothing" in this expression and I should use if-else or switch. thanks.
It looks like you're looking for:
m = (n == 1) ? 1 : 0;
Which you could then cascade to:
m = (n == 1) ? 1 : (n == 2) ? 2 : (n == 3) ? 3 : 0;
An important (to me, anyway), aside:
Why are you asking this? If it's because you think that this form will be more efficient than a series of if statements, or a switch, don't. The C# compiler and the .net JIT compiler are really quite clever and they'll transform your code (hopefully!) into its most optimal form. Write your code so its as understandable by yourself, or the developer who has to maintain it after you as it can be. If the performance you get isn't acceptable, then try changing it around but measure to determine what works best (bearing in mind that newer compilers/.net frameworks could well change what happens).
looking for ternary operator in c# will give you relevant results.
an example usage would be
var m = n == 1 ? 1 : 0
Maybe:
m = (n == 1) ? 1 : (n == 2) ? 2 : (n == 3) ? 3 : m;
or
m = n
Edit:
Simplified:
variable2 = (variable1 == value) ?
variable1 :
variable2;
You want this:
m = (n == 1) ? 1 : 0;
To nest them all it would look like this:
m = (n == 1) ? 1 : (n == 2) ? 2 : (n == 3) ? 3 : 0;
But as you can see, this is really a lot less easy to read and understand. It can help to add extra parenthesis, but I think you're better off using an if-else tree.
m = (n == 1) ? 1 : m
Means
M equals 1 if n == 1, else m
FYI the ? is called the Ternery operator. Find usage on MSDN
Best regards,
You could write:
m = (n==1) ? 1 : m;
But IMO that's harder to read and uglier than the original code.
(n == 1) ? m = 1 : 0;
This isn't allowed because C# doesn't allow arbitrary expressions as a statement. Method calls and assignments are allowed, most other expressions aren't.
A statement is executed for its side-effects, an expression for its value. So it's only natural that the outermost part of a statement has a side effect. ?: never has a side-effect, so it's not allowed as a statement.
Try this :
m = (n == 1) ? 1 : 0;
This is not a problem to be solved with a ternary if/else operator - it is clearly an ideal candidate for a switch statement (and using a switch is likely to be much more efficient than using a sequence of ternary operators)
If you wish to transliterate an if statement into ?:, then it's quite simple:
if ({condition}) {then-code}; else {else-code};
becomes
{condition} ? {then-code} : {else-code};
The only restriction is that the then/else code is a single statement.
The primary benefit of ?: (with modern compilers) is that it can be embedded within a statement to significantly compress the source code - sometimes this can aid readability, and sometimes it just serves to obfuscate the meaning of the code - use it with care.

Do a Range Search for a Alphabetic Field

I have a application that I save this in the database:
FromLetter ToLetter
AAA AAZ
ABC MNL
what I need is to search like this AAC and returns record 1 and FBC and return record 2.
Is the same functionality if instead of letter I save dates. I need to do the same query.
I am using SQL Server and Entity Framework, any Idea how to do this?
Should be pretty straight forward. Here is a Linq to Entities solution, ignoring case:
Entity Framework/Linq solution strings:
string yourValue = somevalue;
var result = (from r in db.ExampleTable
where String.Compare(yourValue, r.FromLetter, true) == 1
&& String.Compare(yourValue, r.ToLetter, true) == -1
select r).First();
Dates:
DateTime yourValue = somevalue;
var result = (from r in db.ExampleTable
where yourValue >= r.FromDate
&& yourValue <= r.ToDate
select r).First();
I think it would be much easier to represent the FromLetter and ToLetter attributes using an integer. Especially if the length of the string is always just 3 - you can simply encode the number as:
(((letter1 - 'A') * 26 + (letter2 - 'A')) * 26) + (letter3 - 'A')
This will give you a number between 0 and 26^3 that represents the tripple and can be easily converted back to the string (using modulo and division as when converting numbers between numeric bases). This number fits into Int32 comfortably (up to 6 letters).
Searching for a string within a specified range would then be a simple search for an integer within a numeric range (which is easy to do and efficient).
Genius solution given by.... bunglestink
I wasted plenty of time in researching implementation of "between" clause for string in EF. This is helpful.

LINQ - Selecting a property of an object for further use rather than dereferencing it in each place

string output = (from s in abc.longs
group s by DateTime.FromFileTimeUtc(s).Minutes < 1
.... // so on so forth
The question I have, is I do "DateTime.FromFileTimeUtc(s) like 10 times here, is there any way to do
from s in abc.longs
t = DateTime.FromFileTimeUtc(s).Minutes
group by t < 1
Yes, using the let keyword, which let you declare a symbol you can use later on in the query:
from s in abc.longs
let t = DateTime.FromFileTimeUtc(s).Minutes
group by t < 1
You can find a lot of examples using Google.

User Control VB.Net script Conversion to C#

<script language="VB" runat="server">
Public Data As String = ""
Public Height As Byte = 25
Public WidthMultiplier As Byte = 1
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim dictEncoding As StringDictionary
Dim sbBarcodeImgs As StringBuilder
Dim strEncodedData As String
Dim I As Integer
dictEncoding = New StringDictionary()
dictEncoding.Add("0", "101001101101")
dictEncoding.Add("1", "110100101011")
dictEncoding.Add("2", "101100101011")
dictEncoding.Add("3", "110110010101")
dictEncoding.Add("4", "101001101011")
dictEncoding.Add("5", "110100110101")
dictEncoding.Add("6", "101100110101")
dictEncoding.Add("7", "101001011011")
dictEncoding.Add("8", "110100101101")
dictEncoding.Add("9", "101100101101")
dictEncoding.Add("A", "110101001011")
dictEncoding.Add("B", "101101001011")
dictEncoding.Add("C", "110110100101")
dictEncoding.Add("D", "101011001011")
dictEncoding.Add("E", "110101100101")
dictEncoding.Add("F", "101101100101")
dictEncoding.Add("G", "101010011011")
dictEncoding.Add("H", "110101001101")
dictEncoding.Add("I", "101101001101")
dictEncoding.Add("J", "101011001101")
dictEncoding.Add("K", "110101010011")
dictEncoding.Add("L", "101101010011")
dictEncoding.Add("M", "110110101001")
dictEncoding.Add("N", "101011010011")
dictEncoding.Add("O", "110101101001")
dictEncoding.Add("P", "101101101001")
dictEncoding.Add("Q", "101010110011")
dictEncoding.Add("R", "110101011001")
dictEncoding.Add("S", "101101011001")
dictEncoding.Add("T", "101011011001")
dictEncoding.Add("U", "110010101011")
dictEncoding.Add("V", "100110101011")
dictEncoding.Add("W", "110011010101")
dictEncoding.Add("X", "100101101011")
dictEncoding.Add("Y", "110010110101")
dictEncoding.Add("Z", "100110110101")
dictEncoding.Add("-", "100101011011")
dictEncoding.Add(":", "110010101101")
dictEncoding.Add(" ", "100110101101")
dictEncoding.Add("$", "100100100101")
dictEncoding.Add("/", "100100101001")
dictEncoding.Add("+", "100101001001")
dictEncoding.Add("%", "101001001001")
dictEncoding.Add("*", "100101101101")
strEncodedData = dictEncoding("*") & "0"
For I = 1 To Len(Data)
strEncodedData = strEncodedData & dictEncoding(Mid(Data, I, 1)) & "0"
Next I
strEncodedData = strEncodedData & dictEncoding("*")
sbBarcodeImgs = New StringBuilder()
For I = 1 To Len(strEncodedData)
If Mid(strEncodedData, I, 1) = "1" Then
sbBarcodeImgs.Append("<img src=""images/bar_blk.gif"" width=""" & WidthMultiplier & """ height=""" & Height & """ />")
Else
sbBarcodeImgs.Append("<img src=""images/bar_wht.gif"" width=""" & WidthMultiplier & """ height=""" & Height & """ />")
End If
Next I
litBarcode.Text = sbBarcodeImgs.ToString
End Sub
</script>
<asp:Literal ID="litBarcode" runat="server" />
Primarily the MID and dictionary usage are unfamiliar to me. Can this be completely converted to C#?
StringDictionary is just another collection class so no problem. Mid could still be used as Microsoft.VisualBasic.Mid() if you're willing to import the Visual Basic library to your C# app (nothing bad about that) or it could be rewritten fairly easily.
Edit: Actually, the VB.Net code just seems to use the Mid in the same way as you can use String.Substring so no need to use the Visual Basic library even. (I was thinking of Mid in VB6 that could be either a function or a statement, the function is similar to String.Substring but there's no real easy way to replicate it if it's the statement one but either way, doesn't matter for this code).
Have you tried using the Telerik Converter? I ran your stuff through there and didn't get any errors.
http://www.developerfusion.com/tools/convert/vb-to-csharp/
Yes. Use one of the converter tools mentioned here; only run through the code though, and not the markup parts of it.

Categories