Property re-evaluation in .NET C# property - c#

I have the below property that calculates the sum of a list of integers.
public int OpponentTotalSetPoints => TeamPoints.Skip(1).Sum(t => t);
My questions is does this property get recaculated every time its called? If so would it be beneficial for the below code to store the value so the summing doesn't happen every time its called?
private int? opponentTotalSetPoints;
public int OpponentTotalSetPoints
{
get
{
if (opponentTotalSetPoints.HasValue)
return opponentTotalSetPoints.Value;
opponentTotalSetPoints = TeamPoints.Skip(1).Sum(t => t);
return opponentTotalSetPoints.Value;
}
}

I would be using something like this
private int? opponentTotalSetPoints;
public int OpponentTotalSetPoints
{
get
{
if (opponentTotalSetPoints==null)
if (TeamPoints.Count >1)
opponentTotalSetPoints = TeamPoints.Skip(1).Sum(t => t);
return opponentTotalSetPoints;
}
}

Related

Mysterious lines in C#

I came across this code:
// A
private readonly int value;
public int RawValue => value;
// B
public int CompareTo(Foo other) => value.CompareTo(other.value);
// C
internal int x => unchecked((value & y) + 1);
Could someone please explain what happened here and what are common ways for using those techniques?
EDIT
Link to the code: click
It's a C# 6 syntax of declaring properties (read-only ones) and methods using expression-bodied members (looks similar to lambda expressions).
public int RawValue => value;
is equivalent to
public int RawValue
{
get { return value; }
}
and
public int CompareTo(Foo other) => value.CompareTo(other.value);
is equivalent to
public int CompareTo(Foo other)
{
return value.CompareTo(other.value);
}

Compare 2 Collections and get Modified items

I have two ObservableCollection in my application, one which contain the items of type StoreSettings
named "oldSettings" anothe collection named "_stores".
public ObservableCollection<StoreSettings> oldSettings;
private ObservableCollection<StoreSettings> _stores;
Here is my StoreSettings class
public class StoreSettings :INotifyPropertyChanged
{
private bool _autoAOD;
public bool AutoAOD
{
get { return _autoAOD; }
set { _autoAOD = value;
}
private bool _autoGRN;
public bool AutoGRN
{
get { return _autoGRN; }
set { _autoGRN = value;
}
private bool _directPurchase;
public bool DirectPurchase
{
get { return _directPurchase; }
set { _directPurchase = value;
}
private decimal _gustoreID;
public decimal GUStoreID
{
get { return _gustoreID; }
set { _gustoreID = value;
}
private string _storeCode;
public string Storecode
{
get { return _storeCode; }
set { _storeCode = value;
}
I am updating some of the item's properties through my application, how can i find the modified items
through linq?
this is what i have tried, but it always gives count "0"
List<StoreSettings> result = _vmStoreconfig.oldSettings.Except(_vmStoreconfig.Stores).ToList();
If these two lists contain the same object instances, then it won't work because changes to object properties in one list will be applied to the other list also (since they are the same instances).
This means that you have to either:
clone objects before changing them, or
create a new instance on each change.
If they are not the same instances (i.e. if they are cloned or came through a database roundrip), then you need to provide a way for the runtime to compare individual properties.
You can either override the Equals method of the StoreSettings, or use a custom equality comparer for your StoreSettings class.
Something like:
public class StoreSettingsEqualityComparer : IEqualityComparer<StoreSettings>
{
public bool Equals(StoreSettings x, StoreSettings y)
{
if (object.ReferenceEquals(x, null))
return object.ReferenceEquals(y, null);
return
x.AutoAOD == y.AutoAOD &&
x.AutoGRN == y.AutoGRN &&
...
}
public int GetHashCode(StoreSettings obj)
{
unchecked
{
var h = 31;
h = h * 7 + obj.AutoAOD.GetHashCode();
...
return h;
}
}
}
And then use an overload of Enumerable.Except which accepts a custom comparer:
var comparer = new StoreSettingsEqualityComparer();
var results = first.Except(second, comparer).ToList();
This should get you the changes
List<StoreSettings> changes = _vmStoreconfig.oldSettings.FindAll(delegate(StoreSettings item1)
{
StoreSettings found = _vmStoreconfig.Stores.Find(delegate(StoreSettings item2) {
// Specify comparisons between properties here
return item2.propertyA == item1.propertyA ...;
}
return found != null;
});

Using Generics to Multiply Integers

I have a class called GenericItem (first time using generics), suppose i wanted to multiply two items if they were of the type integer, as you can see I am trying it in the method returnCounterMultiply, but it does not allow me to multiply them although i am trying to convert them and also checking if they are of type integer.
namespace Components
{
public class GenericItem<T>
{
private T data;
private T counter;
public T Data
{
get { return data; }
set { data = value; }
}
public GenericItem(){}
public GenericItem(T _data)
{
data = _data;
}
public T returnCounterMultiply(T value)
{
int c = 0;
int d = 0;
if (counter.GetType() == typeof(int) && value.GetType() == typeof(int))
{
//cant multiply two of type T, why if i am converting to int?.
return (T)Convert.ChangeType(counter, typeof(Int32)) * (T)Convert.ChangeType(value, typeof(Int32));
}
return value;
}
}
}
I would appreciate some explanation on this as this is the first time I am working on it (this is just a sample class for understanding this GENERICS INTRO and this GENERICS CLASSES, but still having trouble understanding it.
I don't see what your trying to achieve, but if you have to do it I think you have to use an interface:
public interface IMultiplyable<T>
{
T Multiply(T x);
}
public class Int : IMultiplyable<Int>
{
private int _data { get; set; }
public Int(int data)
{
_data = data;
}
public Int Multiply(Int x)
{
return new Int(_data * x._data);
}
public override string ToString()
{
return _data.ToString();
}
}
public class GenericItem<T> where T : IMultiplyable<T>
{
private T data;
private T counter;
public T Data
{
get { return data; }
set { data = value; }
}
public GenericItem() { }
public GenericItem(T _data)
{
data = _data;
}
public T returnCounterMultiply(T value)
{
return Data.Multiply(value);
}
public override string ToString()
{
return Data.ToString();
}
}
Usage:
var a = new GenericItem<Int>(new Int(4));
MessageBox.Show(a.returnCounterMultiply(new Int(5)).ToString()); //20
In my opinion, using generics in this case is an overkill.
It would be nice that generic constraints support something like:
// T parameter is a type which overloads "+" operator...
where T : +
In your concrete case, I would argue you're going in the wrong way. Why don't you just create a class to implement such math operations where properties are typed as int?
Generics work better when T parameter (or any other parameter, of course...) can be constrained to receive types which have:
A public parameterless constructor.
Inherits or implements a class/interface
You need to constraint that T must be a class and not a struct...
When you go into a problem when using generics requires a type conversion, I believe you defeated the point of generics!
You can do something like this:
public class GenericItem<T>
{
private T data;
public T Data
{
get { return data; }
set { data = value; }
}
public GenericItem(){}
public GenericItem(T _data)
{
data = _data;
}
private Dictionary<Type, Delegate> operations =
new Dictionary<Type, Delegate>()
{
{ typeof(int), (Func<int, int, int>)((x, y) => x * y) },
{ typeof(string), (Func<string, string, string>)((x, y) => x + " " + y) },
};
public T returnCounterMultiply(T value)
{
if (operations.ContainsKey(typeof(T)))
{
var operation = (Func<T, T, T>)(operations[typeof(T)]);
return operation(data, value);
}
return value;
}
}
You just need to define, in the dictionary, one operation per valid types you're going to want to use and it just works without any converting of types (except to cast to the Func).
I had these test results:
var gii = new GenericItem<int>(42);
var xi = gii.returnCounterMultiply(2);
// xi == 84
var gis = new GenericItem<string>("Foo");
var xs = gis.returnCounterMultiply("Bar");
// xs == "Foo Bar"
Your problem has nothing to do with generics but with basic C# casting priority:
//cant multiply two of type T, why if i am converting to int?.
return
(T)Convert.ChangeType(counter, typeof(Int32))
*
(T)Convert.ChangeType(value,typeof(Int32));
You do not multiply int but T - and T being a generic type you can only use methods that are ddefined in your generics contraint, which you have none, so no multiply on it.
If you want to multiply int, then do so:
(T) (
((Int32)Convert.ChangeType(counter, typeof(Int32)))
*
((Int32)Convert.ChangeType(value,typeof(Int32)))
);
See the difference?
Basically in your code you deal with T in the multiplication, here I deal with Int32. And factually if T is a Int32 (as you tested before in the IF statement) you can just skip the convert and cast:
(T) (
((Int32)counter)
*
((Int32)value)
);
Now, generics are a bad example for maths as you can not use operations on generics - sadly. This is an abuse of the concept, but I take it was meant as a learning exercise and thus focused on that part on my answer.
I too tried this once and had to find out that there is no pretty way to do it with generics. You cannot do it as generic as in C++.
As an alternative, you may wrap your data types and use a common interface:
interface IMathOps
{
object Value { get; }
void Add(IMathOps other);
// other methods for substraction etc.
}
class IntWrapper : IMathOps
{
public int value;
public void Add(IMathOps other)
{
if(other is IntWrapper)
{
this.value += (int)other.Value;
}
}
public object Value { get { return this.value; } }
}
// class FloatWrapper : IMathOps ...
I think you should use where (generic type constraint). So it will give error at compile time if T is not int.
public T returnCounterMultiply(T value) where T : int
{
int c = 0;
int d = 0;
return c*d;
}

How to refer to the a properties accessor and mutator (getter/setter)

I am wondering if there is a high performant way to refer to a properties getter or setter. For example, how would I fill in the details for the second example class below
public class Example
{
public Example()
{
Action<int> setter = SetX;
Func<int> getter = GetX;
}
public int GetX() { return 0; }
public void SetX(int value){}
}
public class Example2
{
public Example2()
{
Action<int> setter = ...;
Func<int> getter = ...;
}
public int X
{
get{ return 0; }
set{}
}
}
I know I could create lamdas myself like so: Action<int> setter = x => X = x . However one of the reasons I wish to do this is to compare the references themselves in other parts of the application. So I actually wish to use the references to identify the particular property.
For example, I would want this to succeed :
var example = new Example();
Func<int> something = example.GetX;
Func<int> somethingElse = example.GetX;
bool equality = something.Equals(somethingElse);
Only with using properties.
I imagine this could be accomplished with reflection, however it would be likely for many of these operations to occur 30 times a second or so throughout my application, so I am hesitant to use a solution like that rather then just declaring GetX and SetX methods, even though that seems clumsy.
The end goal is to create a syntaticly simple way to both set a field, and inform those who have been linked up that it has been set, and to avoid the use of strings to accomplish it. Here's an example not using Properties, however the linkages would be made with additional abstractions
public class Example
{
public event Action<Delegate> Change;
int x = 0;
public int GetX() { return x; }
public void SetX(int value)
{
SetField(ref x, value, GetX);
}
protected void SetField<T>(ref T t, T value, Func<T> getter)
{
if (!EqualityComparer<T>.Default.Equals(getter(), value))
{
t = value;
if(Change != null)
Change(getter);
}
}
}
var example = new Example();
example.Change += getter =>
{
Func<int> getX = example.GetX;
if (getter.Equals(getX))
{
this.Log("x changed to: " + getX());
}
};
example.SetX(5); // change is logged
I think reflection is the only way to do this:
public Example2()
{
var prop = this.GetType().GetProperty("X");
Action<int> setter = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), this, prop.GetSetMethod());
Func<int> getter = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), this, prop.GetGetMethod());
}
But as you said, reflection is not particularly fast. You could define internal getters / setters as methods and bind to those, but that's not exactly what you were asking for either:
public Example2()
{
Action<int> setter = this.GetX;
Func<int> getter = this.SetX;
}
private int GetX() { return 0; }
private void SetX(int value) { }
public int X
{
get { return GetX(); }
set { SetX(value); }
}

C# Linq, Searching for same items in two lists

we have the following setup:
We have a array of objects with a string in it (xml-ish but not normalized) and we have a list/array of strings with id.
We need to find out if a string from that list with id's is also pressent in one of the objects.
Here we have a setup that we have tried:
public class Wrapper
{
public string MyProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Wrapper> wrappers = new List<Wrapper>()
{
new Wrapper{ MyProperty = "<flkds,dlsklkdlsqkdkqslkdlqk><id>3</id><sqjldkjlfdskjlkfjsdklfj>"},
new Wrapper{ MyProperty = "<flkds,dlsklkdlsqkdkqslkdlqk><id>2</id><sqjldkjlfdskjlkfjsdklfj>"}
};
string[] ids = { "<id>0</id>", "<id>1</id>", "<id>2</id>" };
var props = wrappers.Select(w => w.MyProperty);
var intersect = props.Intersect(ids, new MyEquilityTester());
Debugger.Break();
}
}
class MyEquilityTester: IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return x.Contains(y);
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
Edit:
What we expect is when we do a .Any() on intersect that is says true because wrappers has a object with a prop that contains <id>2</id>, intersect is null.
If we are using the wrong method please say. It should work as fast as posible. A simple true when found will do!
For your case, you could write your IEqualitycomparer like this:
class MyEquilityTester: IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return x.Contains(y) || y.Contains(x);
}
public int GetHashCode(string obj)
{
return 0;
}
}
and it will find
<flkds,dlsklkdlsqkdkqslkdlqk><id>2</id><sqjldkjlfdskjlkfjsdklfj>
This works because GetHashCode always return 0, and the x.Contains(y) || y.Contains(x) check.
Another not-so-hacky solution is to use a Where in combination with Any
IEnumerable<String> intersect = props.Where(p => ids.Any (i => p.Contains(i)));
or replace the Where with another Any if you don't care about the actual items and you only want a true or false.
bool intersect = props.Any(p => ids.Any (i => p.Contains(i)));
wrappers.Where(w=>ids.Any(i=>w.MyProperty.Contains(i)))

Categories