is correct translated code C# to Java? [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Ok i Edited post to short version i want to ask about methods in c#: TryGetValue and sorting list by the compare (IComparator).
I need write this methods in Java so I wrote this code. Asking to developers which know both this language is that correct??
1) First question- TryGetValue is that methods wrote in Java make the same?
c#:
Node value;
if (!nodes.TryGetValue(nodeId,out value)) return false;
to Java:
Node value;
if (!nodes.containsKey(nodeId)){
return false;
}else{
value = nodes.get(nodeId);
}
2)And Sorting by the comparator in java work the same?
static int compareNodes(Node n1, Node n2)
{
if (n1.f > n2.f) return 1;
if (n1.f < n2.f) return -1;
return 0;
}
list.Sort(compareNodes);
And this in Java:
#Override
public int compare(Node nodeFirst, Node nodeSecond) {
if (nodeFirst.f > nodeSecond.f)
return 1;
if (nodeFirst.f < nodeSecond.f)
return -1;
return 0;
}
Collections.sort(nodeList, new OpenList());

After just a quick glance over your code, I can't see any real problems with it. No guarantees though.
If you really want to be sure, you should probably create unit-tests to verify the behavior in both C# and in Java. That will require a little more work, but will be a lot safer than depending on reviews here.

Related

Parameters in parentheses after a method name: what are they and what do they do? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Newb to C# and OOP. My journey thus far has been to take code bases that I've inherited from former developers and either address issues, or add enhancements, whilst trying to understand said code bases' structures from front-to-back.
I'm having trouble fully grasping the concept around the parameters which follow the initial declaration of a method. Here's an example of a method I'm working with:
public List<Entity> ParseCsvFile(List<string> entries, string urlFile)
{
entries.RemoveAt(entries.Count - 1);
entries.RemoveAt(0);
List<Entity> entities = new List<Entity>();
foreach (string line in entries)
{
Entity entityManagement = new Entity();
string[] lineParts = line.Split('|');
entityManagement.Identifier = lineParts[0];
entityManagement.ProductId = 1234;
entityManagement.Category = "ABCDE";
entities.Add(entityManagement);
}
return entities;
}
The part after ParseCsvFile in parentheses: (List<string> entries, string urlFile)
Could someone explain what these are and what they do, perhaps with metaphors/analogies/real-world examples?
It might be easier to see their purpose if you look at a simpler function for example:
public int Add(int number1, int number2)
{
return number1 + number 2;
}
Above there is a function that adds two numbers together and returns the result. It is a set of instructions to follow. How can it follow the instructions if it doesn't know what numbers to use.
That's where calling the function comes in.
for example:
var result = Add(2, 5);
In this scenario result = 7.
2 is replacing number1 in the function and 5 is replacing number2.

Initialize int variable to minus one in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I've come across some code where the variables are initialized to minus one. That's in some old code, is there any reason behind that? Because as far as I know all value types are initialized to zero.
I've tested the code and it doesn't change anything to leave the int variable uninitialized or with minus one, the result is the same.
Would you enlighten me?
class Program
{
static void Main()
{
SampleDelegate del = new SampleDelegate(SampleMethodOne);
del += SampleMethodTwo;
int Number = -1; //or -> int Number;
int returnedValue = del(out Number);
Console.WriteLine("returnedValue = {0}", returnedValue);
Console.ReadLine();
}
public static int SampleMethodOne(out int Number)
{
return Number = 1;
}
public static int SampleMethodTwo(out int Number)
{
return Number = 3;
}
}
public delegate int SampleDelegate(out int Number);
/returns 2
TL;DR: it depends, maybe there is no answer
Possible answer:
Initializing variable is better. you never know how it can be used in some later functions where having an unexpected value may be dangerous (when the code is optimized, you cannot be sure of the default value if not initialized).
In some case, an int may be used for some compatibility reason in the API when you just need an uint. In such a case, initializing to a negative value may be an easy way to detect an unset/invalid value.
No real reason, just an habit from the developer. I agree with comments, ask him if possible

Early return when an Enumerable has more then X elements in Linq [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What is the most performant way in Linq to write:
return enumerable.Count() > x;
I'm at least looking for a solution that:
doesn't involve counting out the whole enumerable.
preferably standard .NET Linq.
should work on different providers.
Note that enumerable.Any() works really well for more then 0, but I'm looking for a solution that checks for more than x.
Example:
Think of a very large enumerable that is build with yield return.
What about simple:
return enumerable.Skip(x).Any();
I think that is what you are looking for.
There's no built-in LINQ method that will give the most efficient solution. Basically you would want to check if the IEnumerable<T> has a Count property (via ICollection<T>) and if not enumerate it.
public static class MoreEnumerable
{
public static bool HasAtLeast<T>(this IEnumerable<T> source, int count)
{
if (source is ICollection<T>)
{
return ((ICollection<T>)source).Count > count;
}
else if (source is ICollection)
{
return ((ICollection)source).Count > count;
}
return source.Skip(count).Any();
}
}
I think you want something like this:
public static bool LazyCount<T>(this IEnumerable<T> source, int count)
{
var enumerator = source.GetEnumerator();
int i = 0;
while(enumerator.MoveNext())
{
i++;
if(i > count) return true;
}
return false;
}
The usage would be:
return enumerable.LazyCount(x);
Note: I'm really bad at naming but you should get the idea, you can modify it however you like.
If you just want to use LINQ I would use something like
enumerable.Take(x).Count() == x
Even though I would prefer Selman22 approach
What is the most performant (and beautiful) way in Linq to write:
return enumerable.Count() > x;
What's wrong with just:
return enumerable.Count() > x;
?
If the actual type of enumerable also implements ICollection, then it will just return ICollection.Count which is typically an O(1) opration. For IQueryable, most query providers will turn it into a SELECT COUNT(*) FROM ... which is about as fast as you can get.
So there are relatively few edge cases that will perform better than Count; probably few enough that trying to code for them is counter-productive.
If you want to know if you have more than 5 you can do the following
enumerable.Take(6).Count() == 6

How to optimize C# code evaluating a condition [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
How to optimize the following C# code?
public class SampleClass
{
public bool IsGreaterThenZero(int i)
{
if (i > 0)
return true;
else
return false;
}
}
Since binary comparison operators, such as >, <, and so on, produce a bool result, ou can return i>0 directly, like this:
public bool IsGreaterThenZero(int i) {
return i > 0;
}

Fastest algorithm to compare two collections or list [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need the fastest algorithm in .NET C# to compare two large collections (200000 records in each collection). I need to validate each row of collection 1 with each row of collection 2 and return the row of collection 1 which has duplicate records in collection 2.
Please suggest a linq query or lookup table which ever is faster..The records are like A2368FG,AD5686,B678SD,C68AGFD,...
private bool CheckValidCode(string stdCode, List<COde> CodeMap, out int count)
{
bool bRetVal = true;
count = 1;
try
{
List<COde> tempCodeMap = new List<COde>();
for (int i = 0; i < CodeMap.Count; i++)
{
if (CodeMap[i].StandardCode == (stdCode))
{
tempCodeMap .Add(customerCodeMappings[i]);
if (CodeMap[i + 1].StandardCode == (stdCode))
{
tempCodeMap .Add(CodeMap[i + 1]);
}
break;
}
}
return tempCodeMap ;
}
}
Are they simple string objects in each? If so, you can use something like
Collection1.Intersect(collection2)
Which will return all record that exist in both collections.
Is that what you wanted? It is not clear from your question if you want to find records that exist in collection1 and multiple times in collection2. If that is what you want, you will need to dig deeper.
Methods like Intersect() etc. should help.
Don't use collections, use Set<T> classes (or convert your collections to sets).
Then you can call methods like Intersect(), it is just faster (but you trade of memory for speed)

Categories