c#: Not finding object in list - c#

I am using LINQ .Find() and it's not stopping when it finds a match. I have:
List<ipFound> ipList = new List<ipFound>();
ipFound ipTemp = ipList.Find(x => x.ipAddress == srcIP);
if (ipTemp == null) {
// this is always null
}
public class ipFound
{
public System.Net.IPAddress ipAddress;
public int bytesSent;
public int bytesReceived;
public int bytesTotal;
}
Any ideas? I'm going nuts over here.
Thanks!

You need to use .Equals instead of ==.
var a = IPAddress.Parse("1.2.3.4");
var b = IPAddress.Parse("1.2.3.4");
Console.WriteLine(a == b); // False
Console.WriteLine(a.Equals(b)); // True
In the sample above, a == b is False because those are two different objects. However, a.Equals(b) is True because they have equal values.

Use IPAddress.Equals instead of comparing references (==):
ipFound ipTemp = ipList.Find(x => x.ipAddress.Equals(srcIP));
As a side note, usually class names are PascalCased (IPFound vs. ipFound)
Example: http://ideone.com/lAeiMm

Related

Partial short circuit boolean evaluation in Javascript or C#

Is there a way, in JavaScript or C#, to determine the outcome of a logical expression before the
values of all variables have been retrieved?
Or to put it differently; can an expression be evaluated such that it returns either 'true', 'false', or 'maybe'? Wherein 'maybe' indicates that more data is needed.
To explain: I have a process in which it takes some time to retrieve data from the database backend and I would like to see if we can skip retrieving certain data if not necessary. But the logical expressions have been predetermined and can not be changed or taken apart.
For instance, consider the following expression:
((a = 1) and (b = 2)) or (c = 3)
There are several possibilities:
If a and b have been retrieved but c has not yet been retrieved:
If a=1 and b=2 then the expression will always return true and I can skip retrieving the value for c
If a=0 and b=2 then the first part will be false, and I need to retrieve the value for c in order to being able to determine the outcome
If c has been retrieved, but and a and b have not yet been retrieved.
If c=3 then the expression will always return true and I can skip retrieving the value for a and b.
If c=2 then the first part will be false, and I need to retrieve the value for a and b in order to being able to determine the outcome
In these situations, just knowing that an outcome is already determined, or that more data is needed can significantly speed up a process.
Does anybody have an idea? A process, function, algorithm?
So to cover your very specific code, you can simply use the following:
if(CHasValue())
return (c == 3) or ((a == 1) and (b == 2))
else
return ((a == 1) and (b == 2)) or (c == 3)
short circuiting of operators will take care of the rest.
This doesn't scale very well with more complex expressions though. In order to really cover any arbitrary boolean expression you really need to create your own new type, and corresponding boolean operators.
We'll start out with an interface defining a boolean value that may or may not have computed its value yet:
public interface IComputableBoolean
{
public bool Value { get; }
public bool ValueComputed { get; }
}
The first implementation is the easy one; it's a computable boolean representing a value that we already know:
public class ComputedBoolean : IComputableBoolean
{
public ComputedBoolean(bool value)
{
Value = value;
}
public bool Value { get; private set; }
public bool ValueComputed { get { return true; } }
}
Then there's the slightly more complex case, the boolean value that is generated based on a function (presumably something that is potentially long running, or that has side effects). It will take a delegate that computes the expression, evaluate it the first time the value is requested, and return a cached value (and indicate that it has computed its value) from then on.
public class DeferredBoolean : IComputableBoolean
{
private Func<bool> generator;
private bool? value = null;
public DeferredBoolean(Func<bool> generator)
{
this.generator = generator;
}
public bool Value
{
get
{
if (value != null)
return value.Value;
else
{
value = generator();
return value.Value;
}
}
}
public bool ValueComputed { get { return value != null; } }
}
Now we just need to create And, Or, and Not methods that apply to this interface. They should first check to see if enough values are computed to allow it to short circuit, and if not, they should create a deferred boolean representing the computation of the value. This propagation of deferred values is important, because it allows complex boolean expressions to be composed and still properly short circuit with the minimal amount of needed computation.
public static IComputableBoolean And(
this IComputableBoolean first,
IComputableBoolean second)
{
if (first.ValueComputed && !first.Value ||
second.ValueComputed && !second.Value)
return new ComputedBoolean(false);
else
return new DeferredBoolean(() => first.Value && second.Value);
}
public static IComputableBoolean Or(
this IComputableBoolean first,
IComputableBoolean second)
{
if (first.ValueComputed && first.Value ||
second.ValueComputed && second.Value)
return new ComputedBoolean(true);
else
return new DeferredBoolean(() => first.Value && second.Value);
}
The Not operation is a bit different in that it can't short circuit at all, but it's still important to have in that it continues to defer evaluation of the given boolean expression, because it may end up not being needed.
public static IComputableBoolean Not(
this IComputableBoolean boolean)
{
if (boolean.ValueComputed)
return new ComputedBoolean(boolean.Value);
else
return new DeferredBoolean(() => boolean.Value);
}
We can now represent the expression that you have like so (using actual long running operations to compute a, b, and/or c as needed):
var a = new DeferredBoolean(() => false);
var b = new DeferredBoolean(() => true);
var c = new DeferredBoolean(() => false);
var expression = a.And(b).Or(c);
bool result = expression.Value;
Assuming a, b, c are truthy once they are loaded, and falsy beforehand (or perhaps a,b,c contain a "loaded" property you could check):
var isValid = false;
if (a && b) {
if (a == 1 && b == 2) {
isValid = true;
}
}
if (!isValid && c) {
if (c == 3) {
isValid = true;
}
}

Modifying values within a list

I've been trying to write a program which can scan a raw data file and normalize it for data mining processes, I've trying to read the data from the file and store it in a list this way:
public static List<Normalize> NF()
{
//Regex r = new Regex(#"^\d+$");
List<Normalize> N = new List<Normalize>();
StreamReader ss = new StreamReader(#"C:\Users\User\Desktop\NN.txt");
String Line = null;
while (!ss.EndOfStream) {
Line = ss.ReadLine();
var L = Line.Split(',').ToList();
N.Add(new Normalize { age = Convert.ToInt16(L[0]),
Sex = L[1],
T3 = Convert.ToDouble(L[2]),
TT4 = Convert.ToDouble(L[3]),
TFU = Convert.ToDouble(L[4]),
FTI = Convert.ToDouble(L[5]),
RC = L[6],
R = L[7]
});
}
return N;
}
}
struct Normalize {
public int age;
public String Sex;
public double T3;
public double TT4;
public double TFU;
public double FTI;
public String RC;
public String R;
}
At this moment I want to go through the list that I've made and categorize the data , similar to this :
var X= NF();
for (int i = 0; i < X.Count; i++) {
if (X[i].age > 0 && X[i].age <= 5) { // Change the X[i].age value to 1 }
else if (X[i].age > 5 && X[i].age <= 10) { // Change the X[i].age value to 2 }
...
}
But the compiler says X[i].[variable name] is not a variable and cannot be modified in this way. My question is, what would be an efficient way to perform this operation.
struct Normalize is a value type, not a reference type, therefore you cannot change its fields like that. Change it to class Normalize
Change struct Normalize to class Normalize and iterate with foreach loop. It's way cleaner.
You could also set variables to private and use getters/setters to check/set variable.
foreach (Normalize x in X)
{
if (x.getAge() > 0 && x.getAge() <= 5)
x.setAge(1)
...
}
Edit:
just saw you already got your answer
Modifying struct field is fine as long as it's a single entity (Given its a mutable struct). This is possible -
var obj = new Normalize();
obh.Age = 10;
But in your case you are accessing the struct using indexer from the list.
Indexer will return copy of your struct and modifying the value won't reflect it back to the list which ain't you want.
Hence compiler is throwing error to stop you from writing this out.
As Alex mentioned, you should go for creating class instead of struct if you want to modify it.
On a side note, its always advisable to have immutable structs instead of mutable structs.

Using Linq Except not Working as I Thought

List1 contains items { A, B } and List2 contains items { A, B, C }.
What I need is to be returned { C } when I use Except Linq extension. Instead I get returned { A, B } and if I flip the lists around in my expression the result is { A, B, C }.
Am I misunderstanding the point of Except? Is there another extension I am not seeing to use?
I have looked through and tried a number of different posts on this matter with no success thus far.
var except = List1.Except(List2); //This is the line I have thus far
EDIT: Yes I was comparing simple objects. I have never used IEqualityComparer, it was interesting to learn about.
Thanks all for the help. The problem was not implementing the comparer. The linked blog post and example below where helpful.
If you are storing reference types in your list, you have to make sure there is a way to compare the objects for equality. Otherwise they will be checked by comparing if they refer to same address.
You can implement IEqualityComparer<T> and send it as a parameter to Except() function. Here's a blog post you may find helpful.
edit: the original blog post link was broken and has been replaced above
So just for completeness...
// Except gives you the items in the first set but not the second
var InList1ButNotList2 = List1.Except(List2);
var InList2ButNotList1 = List2.Except(List1);
// Intersect gives you the items that are common to both lists
var InBothLists = List1.Intersect(List2);
Edit: Since your lists contain objects you need to pass in an IEqualityComparer for your class... Here is what your except will look like with a sample IEqualityComparer based on made up objects... :)
// Except gives you the items in the first set but not the second
var equalityComparer = new MyClassEqualityComparer();
var InList1ButNotList2 = List1.Except(List2, equalityComparer);
var InList2ButNotList1 = List2.Except(List1, equalityComparer);
// Intersect gives you the items that are common to both lists
var InBothLists = List1.Intersect(List2);
public class MyClass
{
public int i;
public int j;
}
class MyClassEqualityComparer : IEqualityComparer<MyClass>
{
public bool Equals(MyClass x, MyClass y)
{
return x.i == y.i &&
x.j == y.j;
}
public int GetHashCode(MyClass obj)
{
unchecked
{
if (obj == null)
return 0;
int hashCode = obj.i.GetHashCode();
hashCode = (hashCode * 397) ^ obj.i.GetHashCode();
return hashCode;
}
}
}
You simply confused the order of arguments. I can see where this confusion arose, because the official documentation isn't as helpful as it could be:
Produces the set difference of two sequences by using the default equality comparer to compare values.
Unless you're versed in set theory, it may not be clear what a set difference actually is—it's not simply what's different between the sets. In reality, Except returns the list of elements in the first set that are not in the second set.
Try this:
var except = List2.Except(List1); // { C }
Writing a custom comparer does seem to solve the problem, but I think https://stackoverflow.com/a/12988312/10042740 is a much more simple and elegant solution.
It overwrites the GetHashCode() and Equals() methods in your object defining class, then the default comparer does its magic without extra code cluttering up the place.
Just for Ref:
I wanted to compare USB Drives connected and available to the system.
So this is the class which implements interface IEqualityComparer
public class DriveInfoEqualityComparer : IEqualityComparer<DriveInfo>
{
public bool Equals(DriveInfo x, DriveInfo y)
{
if (object.ReferenceEquals(x, y))
return true;
if (x == null || y == null)
return false;
// compare with Drive Level
return x.VolumeLabel.Equals(y.VolumeLabel);
}
public int GetHashCode(DriveInfo obj)
{
return obj.VolumeLabel.GetHashCode();
}
}
and you can use it like this
var newDeviceLst = DriveInfo.GetDrives()
.ToList()
.Except(inMemoryDrives, new DriveInfoEqualityComparer())
.ToList();

Avoiding calls to mscorlib when comparing strings?

Is there a possible way that let me compare strings without calling the op_Equality function is mscorlib?
For example:
string s1 = "hi";
if(s1 == "bye")
{
Console.Writeline("foo");
}
Compiles to:
IL_0003: call bool [mscorlib]System.String::op_Equality(string, string)
And looking at op_Equality at mscorlib from GAC it calls another method Equals(string, string)
Code:
public static bool Equals(string a, string b)
{
return a == b || (a != null && b != null && string.EqualsHelper(a, b));
}
it uses the op code bne.une.s to compare those strings.
Now back at my question, how can I compare 2 strings without calling any function from the mscorlib like the method Equals does.
Now back at my question, how can I compare 2 strings without calling any function from the mscorlib like the method Equals does.
You can't - at least not without writing your own string comparison method from scratch.
At some point, you'd have to at least call String.Equals(a,b) (in order to have the private EqualsHelper method called, which does the actual comparison), which is also defined in mscorlib.
You could call Equals directly if you wish to avoid the operator call, though:
string s1 = "hi";
if (string.Equals(s1, "bye"))
{
Console.WriteLine("foo");
}
This would avoid the call to op_Equality, bypassing it and calling Equals directly.
That being said, there is really no reason to avoid calling op_Equality on strings in the first place...
It seems like you are asking for a string comparison function. Strings are basically arrays of characters that you can index in a similar fashion. Here is a simple string comparison algorithm.
public static bool Equals(string left, string right)
{
if (ReferenceEquals(left, null)) return ReferenceEquals(right, null);
if (left.Length != right.Length) return false;
for (int i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
return false;
}
return true;
}
Having shown you that, there is no reason to avoid the mscorlib implementation, since my example makes several calls to mscorlib.
This is another way to compare:
string s1 = "Hello";
bool same = s1.CompareTo("Hello") == 0;
bool different = s1.CompareTo("GoodBye") != 0;
Console.WriteLine(same);
Console.WriteLine(different);
In this case, both should report "True" to the console.
Another way:
private static bool CheckEqual(string s1, string s2)
{
char[] c1 = (s1 == null) ? new char[0] : s1.ToCharArray();
char[] c2 = (s2 == null) ? new char[0] : s2.ToCharArray();
if (c1.Length != c2.Length) { return false; }
for (int i = 0; i < c1.Length; i++)
{
if (!c1[i].Equals(c2[i])) { return false; }
}
return true;
}
Given that the String class is provided by mscorlib, there is absolutely no way to compare two strings without using mscorlib. Even just using the indexer to get each character calls into mscorlib.
The only way to avoid mscorlib is to not use the .Net runtime, but that's pretty difficult if you want to use C#.

Why do 2 delegate instances return the same hashcode?

Take the following:
var x = new Action(() => { Console.Write("") ; });
var y = new Action(() => { });
var a = x.GetHashCode();
var b = y.GetHashCode();
Console.WriteLine(a == b);
Console.WriteLine(x == y);
This will print:
True
False
Why is the hashcode the same?
It is kinda surprising, and will make using delegates in a Dictionary as slow as a List (aka O(n) for lookups).
Update:
The question is why. IOW who made such a (silly) decision?
A better hashcode implementation would have been:
return Method ^ Target == null ? 0 : Target.GetHashcode();
// where Method is IntPtr
Easy! Since here is the implementation of the GetHashCode (sitting on the base class Delegate):
public override int GetHashCode()
{
return base.GetType().GetHashCode();
}
(sitting on the base class MulticastDelegate which will call above):
public sealed override int GetHashCode()
{
if (this.IsUnmanagedFunctionPtr())
{
return ValueType.GetHashCodeOfPtr(base._methodPtr);
}
object[] objArray = this._invocationList as object[];
if (objArray == null)
{
return base.GetHashCode();
}
int num = 0;
for (int i = 0; i < ((int) this._invocationCount); i++)
{
num = (num * 0x21) + objArray[i].GetHashCode();
}
return num;
}
Using tools such as Reflector, we can see the code and it seems like the default implementation is as strange as we see above.
The type value here will be Action. Hence the result above is correct.
UPDATE
My first attempt of a better implementation:
public class DelegateEqualityComparer:IEqualityComparer<Delegate>
{
public bool Equals(Delegate del1,Delegate del2)
{
return (del1 != null) && del1.Equals(del2);
}
public int GetHashCode(Delegate obj)
{
if(obj==null)
return 0;
int result = obj.Method.GetHashCode() ^ obj.GetType().GetHashCode();
if(obj.Target != null)
result ^= RuntimeHelpers.GetHashCode(obj);
return result;
}
}
The quality of this should be good for single cast delegates, but not so much for multicast delegates (If I recall correctly Target/Method return the values of the last element delegate).
But I'm not really sure if it fulfills the contract in all corner cases.
Hmm it looks like quality requires referential equality of the targets.
This smells like some of the cases mentioned in this thread, maybe it will give you some pointers on this behaviour. else, you could log it there :-)
What's the strangest corner case you've seen in C# or .NET?
Rgds GJ
From MSDN :
The default implementation of
GetHashCode does not guarantee
uniqueness or consistency; therefore,
it must not be used as a unique object
identifier for hashing purposes.
Derived classes must override
GetHashCode with an implementation
that returns a unique hash code. For
best results, the hash code must be
based on the value of an instance
field or property, instead of a static
field or property.
So if you have not overwritten the GetHashCode method, it may return the same. I suspect this is because it generates it from the definition, not the instance.

Categories

Resources