C#: Getter and setter expression for array property - c#

How can I write the getter and setter expression for array property CoolerFanIsOn in the class CoolerSystem? I showed the similar desired expression for non-array property IsOn of Lamp class.
class CoolerFan{
bool isOn;
public bool IsOn {
get => isOn;
set {
isOn = value;
}
}
}
class CoolerSystem {
private CoolerFan[] = new CoolerFan[5];
private bool[] coolerFanIsOn = new Boolean[5];
// invalid code from now
public bool[] CoolerFanIsOn {
get => coolerFanIsOn[number];
set {
coolerFanIsOn[number] = value;
}
}
}

You can use indexer:
public class CoolerSystem
{
private bool[] _coolerFanIsOn = new Boolean[5];
public bool this[int index]
{
get => _coolerFanIsOn[index];
set => _coolerFanIsOn[index] = value;
}
}
Btw, the => are expression bodied properties which were new in C#6. If you can't use (setter was new in C#7) use the old syntax, indexers have nothing to do with it(C#3):
public bool this[int index]
{
get { return _coolerFanIsOn[index]; }
set { _coolerFanIsOn[index] = value; }
}

You can write an indexer for your class
public bool this[int index]{
get { return coolerFanIsOn[index]; }
set { coolerFanIsOn[index] = value;}
}

Maybe this is what you would like to do:
class CoolerSystem
{
private CoolerFan[] _fans = new CoolerFan[5];
private bool[] _coolerfanIsOn;
public bool[] CoolerFanIsOn
{
get { return _coolerfanIsOn; }
set
{
_coolerfanIsOn = value;
}
}
public bool GetFanState(int number)
{
return CoolerFanIsOn[number];
}
public void SetFanState(int number, bool value)
{
CoolerFanIsOn[number] = value;
}
}

Related

Delete item from inner collection

Inner Collection
public class ItemsDetails
{
//Constructor
public ItemsDetails(int iID,
string sItemName,
Decimal iPrice,
int iQuantity,
int iPostalCode,
bool bisDB,
string SImagePath)
{
this.iID = iID;
this.sItemName = sItemName;
this.iPrice = iPrice;
this.iquantity = iQuantity;
this.iPostalCode = iPostalCode;
this.bisDB = bisDB;
this.sImagePath = SImagePath;
}
public ItemsDetails()
{
}
#region PrivateProperties
private int iID;
private string sItemName;
private Decimal iPrice;
private int iquantity;
private int iPostalCode;
private string sImagePath;
private int iMasterID;
#endregion
//static List<ItemsDetails> itemsDetails = new List<ItemsDetails>();
#region public Properties
public bool bisChanged = false;
public bool bisDB = true;
#endregion
public int IMasterID
{
get
{
return this.iMasterID;
}
set
{
if (this.iMasterID != value)
bisChanged = true;
this.iMasterID = value;
}
}
public bool BisChanged
{
get
{
return this.bisChanged;
}
set
{
this.bisChanged = value;
}
}
public int IPostalCode
{
get
{
return this.iPostalCode;
}
set
{
if (this.iPostalCode != value)
bisChanged = true;
this.iPostalCode = value;
}
}
public int Iquantity
{
get
{
return this.iquantity;
}
set
{
if (this.iquantity != value)
bisChanged = true;
this.iquantity = value;
}
}
public Decimal IPrice
{
get
{
return this.iPrice;
}
set
{
if (this.iPrice != value)
bisChanged = true;
this.iPrice = value;
}
}
public string SItemName
{
get
{
return this.sItemName;
}
set
{
if (this.sItemName != value)
bisChanged = true;
this.sItemName = value;
}
}
public string SImagePath
{
get
{
return this.sImagePath;
}
set
{
if (this.sImagePath != value)
bisChanged = true;
this.sImagePath = value;
}
}
public int IID // unique id
{
get
{
return this.iID;
}
set
{
if (this.iID != value)
bisChanged = true;
this.iID = value;
}
}
}
Main collection
public class ItemsMapping
{
private int itemMasterID;
private string sCatagoryName;
private string sImagePath;
private ICollection<ItemsDetails> iCollectionItemDetails;
public string SImagePath
{
get
{
return this.sImagePath;
}
set
{
this.sImagePath = value;
}
}
public string SCatagoryName
{
get
{
return this.sCatagoryName;
}
set
{
this.sCatagoryName = value;
}
}
public ICollection<ItemsDetails> ICollectionItemDetails
{
get
{
return this.iCollectionItemDetails;
}
set
{
this.iCollectionItemDetails = value;
}
}
public int ItemMasterID
{
get
{
return this.itemMasterID;
}
set
{
this.itemMasterID = value;
}
}
}
Object of collection
Collection<ItemsMapping> objItemCollection = getdata();// from db
Collection<ItemsDetails> objDeleteItems = itemsToDelete();// from selected items
Result i need to delete items from inner collection objItemCollection based on objDeleteItems collection.
I expect without using foreach/for loop. Trying to find solution on linq
Thanks in advance..
Linq (Language-Integrated Query)is for querying, not for modifying (i.e. updating, adding, deleting). Use foreach loop if you want to modify collection.
You can write query which returns set of items without those you want to delete, and then use results of this query instead of your original collection. If you have same instances of ItemsDetails objects in both collections (otherwise you will need to override Equals and GetHashCode of ItemsDetails class), and you don't need duplicates in result:
objItemCollection.ICollectionItemDetails =
objItemCollection.ICollectionItemDetails.Except(objDeleteItems);
But I would go without query. Simple loop will do the job (overriding of Equals and GetHashCode still required if you don't use same instances of ItemsDetails):
foreach(var item in objDeleteItems)
objItemCollection.ICollectionItemDetails.Remove(item);
You can move this logic to extension method
public static void RemoveAll<T>(
this ICollection<T> source, IEnumerable<T> itemsToRemove)
{
if (source == null)
throw new ArgumentNullException("source");
foreach(var item in itemsToRemove)
source.Remove(item);
}
Now code will look like:
objItemCollection.ICollectionItemDetails.RemoveAll(objDeleteItems);

How to change WPF CollectionViewGroup type to custom type and use it in ListCollectionView

How can override the type of View property to my custom type.
My CustomGroupListCollectionView type adds extra property to the Groups property.
During runtime when i observe the type of View property is ListCollectionView, i want to change this to CustomGroupListCollectionView.
public class CollectionViewSourceCustom : CollectionViewSource
{
public new CustomGroupListCollectionView View { get; set; }
}
public class CustomGroupListCollectionView : ListCollectionView
{
private readonly CustomGroup _allGroup;
public CustomGroupListCollectionView(IList list)
: base(list)
{
_allGroup = new CustomGroup("All");
foreach (var item in list)
{
_allGroup.AddItem(item);
}
}
public override ReadOnlyObservableCollection<object> Groups
{
get
{
var group = new ObservableCollection<object>(base.Groups.ToList());
group.Add(_allGroup);
return new ReadOnlyObservableCollection<object>(group);
}
}
}
public class CustomGroup : CollectionViewGroup
{
public CustomGroup(object name)
: base(name)
{
}
public void AddItem(object item)
{
ProtectedItems.Add(item);
}
public override bool IsBottomLevel
{
get { return true; }
}
bool _IsChecked;
public bool IsChecked
{
get { return _IsChecked; }
set { _IsChecked = value; }
}
Visibility _CheckBoxVisibility;
public Visibility CheckBoxVisibility
{
get { return _CheckBoxVisibility; }
set { _CheckBoxVisibility = value; }
}
bool _IsExpanded;
public bool IsExpanded
{
get { return _IsExpanded; }
set { _IsExpanded = value; }
}
Visibility _ExpanderVisibility;
public Visibility ExpanderVisibility
{
get { return _ExpanderVisibility; }
set { _ExpanderVisibility = value; }
}
Visibility _ImageVisibility = Visibility.Collapsed;
public Visibility ImageVisibility
{
get { return _ImageVisibility; }
set { _ImageVisibility = value; }
}
}
CollectionViewSource has a CollectionViewType property, which you can use to determine the type of CollectionView the CollectionViewSource returns, like
<CollectionViewSource x:Key="source" CollectionViewType="{x:Type my:CustomGroupListCollectionView}" Source="{Binding MyData}"/>
As you see, you don't even have to create a new CollectionViewSource class.
If you still persist on using your way I would suggest this code:
public class CollectionViewSourceCustom : CollectionViewSource
{
public CollectionViewSourceCustom()
: base()
{
((ISupportInitialize)this).BeginInit();
this.CollectionViewType = typeof(CustomGroupListCollectionView);
((ISupportInitialize)this).EndInit();
}
}
Hope it helps.

c# casting string to class object

i want to cast a string from database to a class object without having to go over each possible outcome.
so not
if(type.StartsWith("ContactPersonType")){//} else if(type.StartsWith("ContactPersonTitle")){//}
this is what i have so far
private static T Create<T>(IDataRecord record)
{
var properties = typeof(T).GetProperties();
var returnVal = Activator.CreateInstance(typeof(T));
properties.ToList().ForEach(item =>
{
string type = item.GetMethod.ReturnParameter.ParameterType.Name;
if (type.StartsWith("ContactPerson"))
{
Type t = Type.GetType(item.GetMethod.ReturnParameter.ParameterType.ToString());
item.SetValue(returnVal, Convert.ChangeType(record[item.Name].ToString(), t));
}
else if (!type.StartsWith("ObservableCollection"))
{
item.SetValue(returnVal, Convert.ChangeType(record[item.Name].ToString(), item.PropertyType));
}
});
return (T)returnVal;
}
public class ContactPersonType
{
private int _id;
public int ID
{
get { return _id; }
set { _id = value; }
}
private String _name;
public String Name
{
get { return _name; }
set { _name = value; }
}
}
thanks
Use an anonymous collection when you want a certain action to apply to different input values.
foreach(var option in new[] {"ContactPerson", "ContactPersonTitle" }){
if (type.StartsWith(option))
{
Type t = Type.GetType(item.GetMethod.ReturnParameter.ParameterType.ToString());
item.SetValue(returnVal, Convert.ChangeType(record[item.Name].ToString(), t));
}
}

XML serialization C#, not processing certain fields

I have a serialization method as follows:
public string SerializeObject(object obj, Type type)
{
var setting = new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true };
var xml = new StringBuilder();
using (var writer = XmlWriter.Create(xml, setting))
{
var nsSerializer = new XmlSerializerNamespaces();
nsSerializer.Add(string.Empty, string.Empty);
var xmlSerializer = new XmlSerializer(type);
xmlSerializer.Serialize(writer, obj, nsSerializer);
}
return xml.ToString();
}
Which I call as follows:
requestXML = serializer.SerializeObject(InboundIterate, typeof(INBOUND));
The output is as expected for any field I have defined in my structure as a string, but all the decimal values are missing.
For example my output will look like:
<PRODUCT_EXTENSION>
<DIMENSION_UOM>IN</SD_DIMENSION_UOM>
<SALES_UOM>CS</SD_SALES_UOM>
</PRODUCT_EXTENSION>
when I am expecting
<PRODUCT_EXTENSION>
<DIMENSION_UOM>IN</DIMENSION_UOM>
<DIMENSION>15.83</DIMENSION>
<SALES_UOM>CS</SALES_UOM>
<SALES>24</SALES>
</PRODUCT_EXTENSION>
any help would be appreciated, thank you.
class below
public partial class PRODUCT_EXTENSION {
private System.Nullable<decimal> LENGTHField;
private bool LENGTHFieldSpecified;
private System.Nullable<decimal> NET_WEIGHTField;
private bool NET_WEIGHTFieldSpecified;
private string SALES_UOMField;
private string WEIGHT_UOMField;
private List<PRODUCT_EXTENSIONSOURCE_SYSTEM> SOURCE_SYSTEMField;
public PRODUCT_EXTENSION() {
this.SOURCE_SYSTEMField = new List<PRODUCT_EXTENSIONSOURCE_SYSTEM>();
}
public System.Nullable<decimal> LENGTH {
get {
return this.LENGTHField;
}
set {
this.LENGTHField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool SD_LENGTHSpecified {
get {
return this.LENGTHFieldSpecified;
}
set {
this.LENGTHFieldSpecified = value;
}
}
public System.Nullable<decimal> NET_WEIGHT {
get {
return this.NET_WEIGHTField;
}
set {
this.NET_WEIGHTField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool NET_WEIGHTSpecified {
get {
return this.NET_WEIGHTFieldSpecified;
}
set {
this.NET_WEIGHTFieldSpecified = value;
}
}
public string SALES_UOM {
get {
return this.SALES_UOMField;
}
set {
this.SALES_UOMField = value;
}
}
public string SD_WEIGHT_UOM {
get {
return this.WEIGHT_UOMField;
}
set {
this.WEIGHT_UOMField = value;
}
}
public List<PRODUCT_EXTENSIONSOURCE_SYSTEM> SOURCE_SYSTEM {
get {
return this.SOURCE_SYSTEMField;
}
set {
this.SOURCE_SYSTEMField = value;
}
}
}
I've tried your code snippet, and it works fine for me fine with public properties, but if i change the property protection to protected or private. These properties are missing from the XML.
Check your properties.

Dictionary<dynamic, dynamic> Value items can't be accessed. C#

I'm playing around with Dictionaries and the new fancy 4.0 dynamic types inside a dictionary.
I have a Dictionary:
Dictionary<dynamic, dynamic> dynamicDic
And I populate it like this:
dynamicDic.Add("First", new Class1());
dynamicDic.Add("Second", new Class2());
For the sake of testing/practising Class1 and Class2 are quite simple:
public class Class1
{
public string Element { get; set; }
public List<Class2> Class2 { get; set; }
}
public class Class2
{
public string Property { get; set; }
public string Field;
}
I create two other classes that map class1 and class2 and they are virtually the same so ClassMap1 and ClassMap2. I'll just include CalssMap1 though:
public class ClassMap1: BaseClassMap1
{
public ClassMap1()
{
var r = new Class1();
Children = new Dictionary<string, dynamic>
{
{"Element", r.GetType().GetProperty("Element")},
{"Class1", r.GetType().GetProperty("Class1")}
};
Name = "Root";
ObjectType = typeof (Class1);
Parent = "RootElement";
HasParent = false;
HasChildren = true;
IsClass = r.GetType().IsClass;
}
}
And I create a base class: BaseClass1()
public class BaseClass1
{
private String _Name;
public String Name
{
get { return _Name; }
set { _Name = value; }
}
private Type _ObjectType;
public Type ObjectType
{
get { return _ObjectType; }
set { _ObjectType = value; }
}
private String _Parent;
public String Parent
{
get { return _Parent; }
set { _Parent = value; }
}
private Dictionary<string, dynamic> _Children;
public Dictionary<string, dynamic> Children
{
get { return _Children; }
set { _Children = value; }
}
private bool _HasParent;
public bool HasParent
{
get { return _HasParent; }
set { _HasParent = value; }
}
private bool _HasChildren;
public bool HasChildren
{
get { return _HasChildren; }
set { _HasChildren = value; }
}
private bool _IsClass;
public bool IsClass
{
get { return _IsClass; }
set { _IsClass = value; }
}
}
I populate the classes with data, not really important what data :)
Yet when I try to access the values through a Linq statement:
var a = _classObjects.SingleOrDefault(x => x.Key == node.Name).Value;
a only gives me:-
a.Equals(), a.GetType(), a.GetEnumerator() or a.ToString()
I would like to be able to have it do this instead (with intellisense)...
a.Children
a.Name
a.HasParent
etc...
Anyone got any ideas where I'm going wrong?
Oops got that completely wrong... Sorry :|
Edited above...
dynamic classes are all about run-time (NOT compile-time) discovery. How do you expect Intellisense to know what to do?
Using dynamic classes incurs a high performance overhead. I really suggest that you make it: Dictionary<string, dynamic> dynamicDic.
Or define a MyBaseClass and make it: Dictionary<string, MyBaseClass> myDic.

Categories