How to use Collection in loop - c#

Small doubt, In Update method I had int count, let say count == 4, then i am using for loop to get id, version and set.
In this case Id,version and set values getting only the last value, but how to get the all the values
I tried but i feel its wrong and not working,
Created a seperate list for id, version and set,
eg: _details.imageList.Add(logoHeader.LogoID);
public void Updates(AUnit _aUnit, int Id)
{
ImageDetails _details = new ImageDetails(_aUnit, Id);
int count = (int) _aUnit.ReadBits(8);
for (int i = 0; i < (int) count; i++)
{
_details.ID = (int) _aUnit.ReadBits(8);
_details.Version = (int) _aUnit.ReadBits(8);
_details.set = (int) _aUnit.ReadBits(24);
}
_details.Rset = _aUnit.Buffer.Skip(10).Take(_details.set).ToArray();
//MemoryStream ms = new MemoryStream(_details.PortrateImages.First());
//Image image = Image.FromStream(ms);
//Bitmap bmp = new Bitmap(image);
_details.UpdateTime = DateTime.Now.ToString("h:mm:ss tt");
newData.Add(_details);
}
public class ImageDetails
{
public ImageDetails(AUnit _au, int carouselId)
{
carId = carouselId;
_AUnit = _au;
_updateTime = "";
}
private string _updateTime;
public int ID { get; set; }
public int Version { get; set; }
public int set { get; set; }
public int carId { get; set; }
public byte[] Rset { get; set; }
public AUnit _AUnit { get; set; }
public byte[] bytes { get; set; }
public List<byte[]> dataArray = new List<byte[]>();
public string UpdateTime
{
get { return _updateTime; }
set { _updateTime = value; }
}
public List<byte[]> PImages
{
get
{
List<byte[]> Plogos = new List<byte[]>();
if (carId == 2)
{
Plogos.Add(Rset);
}
return Plogos;
}
}
public List<byte[]> LImages
{
get
{
List<byte[]> Llogos = new List<byte[]>();
if (carId == 1)
{
Llogos.Add(Rset);
}
return Llogos;
}
}
}

You could make detail an object(class) and make a list of details.
like,
public class Detail
{
public int Id{get;set;}
public int Version{get;set;}
public int set{get;set;}
}
and make a list of detail like,
var Details = new List<Detail>();
and you could access it using the foreach loop. like,
foreach(var detail in Details){
Console.log(detail.Id)
.....
}
hope this helps.

Related

how do you add get and set for an array in c#

I'm coding a func that inputs an array with different year of birth and prints out the oldest person.
I'm trying to add a validation with get and set but my syntax is wrong.
enter image description here
TL;DR
Properties declaration part:
public class Employee
{
private string _fullName;
private int _yearIn;
public string FullName
{
get => _fullName;
set
{
if (!string.IsNullOrEmpty(value))
{
_fullName = value;
}
}
}
public int YearIn
{
get => _yearIn;
set
{
if (value > 0 && value <= 2020)
{
_yearIn = YearIn;
}
}
}
}
And a usage:
var employees = new List<Employee>();
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Enter Name:");
string name = Console.ReadLine();
Console.WriteLine("Enter Year:");
int yearIn = Convert.ToInt32(Console.ReadLine());
employees.Add(new Employee
{
FullName = name,
YearIn = yearIn
});
}
Update
You can do the same in a bit different manner though:
public class Employee
{
private string _fullName;
private int _yearIn;
public bool IsNameValid { get; set; }
public bool IsYearValid { get; set; }
public string FullName
{
get => _fullName;
set
{
_fullName = value;
IsNameValid = string.IsNullOrEmpty(value);
}
}
public int YearIn
{
get => _yearIn;
set
{
_yearIn = value;
IsYearValid = (value < 0) || (value > 2020);
}
}
}
And later:
Console.WriteLine($"Employee name is: {employees[i].IsNameValid}");
Console.WriteLine($"Employee year is: {employees[i].IsYearValid}");
Update 2
And the last alternative version is that you can use Validation attributes:
public class Employee
{
[Required]
[Range(0, 2020)]
public int YearIn { get; set; }
[Required]
[StringLength(50)]
public string FullName { get; set; }
}
later:
var empl = new Employee{ YearIn = yearIn, FullName = name};
var context = new ValidationContext(empl, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(empl, context, results, true);
Console.WriteLine($"Is model valid: {isValid}");
if (isValid)
{
employees.Add(new Employee
{
FullName = name,
YearIn = yearIn
});
}
You can create wrapper classes over array and use indexer method for accessing the array item.
There in, you can put all your validation logic.
class IntData
{
public IntData(int size)
{
data = new int[size];
}
// Array of temperature values
private int[] data;
public int this[int index]
{
get
{
return data[index];
}
set
{
// Do your validation here
if (value < 5000)
{
data[index] = value;
}
}
}
}
static void Main(string[] args)
{
IntData year = new IntData(3);
year[0] = 2000;
year[1] = 6000; // This value won't set because of validation
year[2] = 4000;
Console.Read();
}

Assign ID to each two columns imported from Excel file

I trying to import data from excel and for each two connected column i store the data into two dimensional list except the last column which will be in a 1D list. i wanna assign an id for each set of data the code get to be able to build a dictionary later for them.
that means for the first( valLat and valLng together ) i want to assign id = 1 and so on for each List
for (int i = 2; i <= rowCount; i++)
{
var pickLocation = new PickLocation();
var valLat = ((Excel.Range)wks.Cells[i, PickLocation.ColumnLat]).Value;
var valLng = ((Excel.Range)wks.Cells[i, PickLocation.ColumnLng]).Value;
if (!(valLat == null) & !(valLng == null))
{
pickLocation.Lat = Convert.ToDouble(valLat);
pickLocation.Lng = Convert.ToDouble(valLng);
ListPickLocations.Add(pickLocation);
}
var setLocation = new SetLocation();
valLat = ((Excel.Range)wks.Cells[i, SetLocation.ColumnLat]).Value;
valLng = ((Excel.Range)wks.Cells[i, SetLocation.ColumnLng]).Value;
if (!(valLat == null) & !(valLng == null))
{
setLocation.Lat = Convert.ToDouble(valLat); ;
setLocation.Lng = Convert.ToDouble(valLng);
ListSetlocations.Add(setLocation);
}
var craneLocation = new CraneLocation();
valLat = ((Excel.Range)wks.Cells[i, CraneLocation.ColumnLat]).Value;
valLng = ((Excel.Range)wks.Cells[i, CraneLocation.ColumnLng]).Value;
if (!(valLat == null) & !(valLng == null))
{
craneLocation.Lat = Convert.ToDouble(valLat); ;
craneLocation.Lng = Convert.ToDouble(valLng);
ListCranelocations.Add(craneLocation);
}
var weight = ((Excel.Range)wks.Cells[i, 10]).Value;
if (!(weight == null))
{
Weights.Add(Convert.ToDouble(weight));
}
var clearance = ((Excel.Range)wks.Cells[2, 12]).Value;
if (!(clearance == null))
{
Clearance = clearance;
}
}
}
}
}
}
public class PickLocation
{
public double Lat { get; set; }
public double Lng { get; set; }
public static int ColumnLat { get; } = 4;
public static int ColumnLng { get; } = 5;
}
public class CraneLocation
{
public double Lat { get; set; }
public double Lng { get; set; }
public static int ColumnLat { get; } = 1;
public static int ColumnLng { get; } = 2;
}
public class SetLocation
{
public double Lat { get; set; }
public double Lng { get; set; }
public static int ColumnLat { get; } = 7;
public static int ColumnLng { get; } = 8;
}

How to fill ObservableCollection from two tables from DataBase?

Trying to populate an ObservableCollection from a database using the Entity Framework. Everything was fine until I started working with linked tables.
I created the DeviceCategory and DeviceComplexity model, and now in the WyeModel I try to integrate them into the DeviceCategoryViewModel. Further, in DeviceCategoryViewModel, I indicated a request for taking information from the database, but I ran into a problem. How to fill in ObservableCollection with this information? I tried different ways, but it didn’t lead to anything, I just got more confused.
DeviceCategoriesViewModel
class DeviceCategoryViewModel
{
TechDContext dc = new TechDContext();
public int Device_category_id { get; set; }
public string Device_category_name { get; set; }
public int Device_complexity_id { get; set; }
public string Device_complexity_name { get; set; }
public static DeviceCategoryViewModel DeviceCaterogyVM(DeviceCategory deviceCategory, DeviceComplexity deviceComplexity)
{
return new DeviceCategoryViewModel
{
Device_category_id = deviceCategory.Device_category_id,
Device_category_name = deviceCategory.Category_name,
Device_complexity_id = deviceCategory.Device_complexity_id,
Device_complexity_name = deviceComplexity.Device_complexity_name
};
}
public void FillDeviceDategories()
{
var q = from cat in dc.DeviceCategories
join com in dc.DeviceComplexities on cat.Device_complexity_id equals com.Device_complexity_id
select new
{
Device_category_id = cat.Device_category_id,
Category_name = cat.Category_name,
Device_complexity_id = com.Device_complexity_id,
Device_complexity_name = com.Device_complexity_name
};
items = q;
deviceCategories = Convert(items);
}
public ObservableCollection<DeviceCategoryViewModel>
Convert(IEnumerable<object> original)
{
return new ObservableCollection<DeviceCategoryViewModel>(original.Cast<DeviceCategoryViewModel>());
}
private IEnumerable<object> items;
public IEnumerable<object> Items
{
get
{
return items;
}
}
private ObservableCollection<DeviceCategoryViewModel> deviceCategories;
public ObservableCollection<DeviceCategoryViewModel> DeviceCategories
{
get
{
FillDeviceDategories();
return deviceCategories;
}
}
DeviceCategory Model
[Table("device_categories")]
public class DeviceCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Device_category_id { get; set; }
public string Category_name { get; set; }
//[ForeignKey]
public int Device_complexity_id { get; set; }
public DeviceCategory()
{
}
public DeviceCategory(string name, int complexity_id)
{
Category_name = name;
Device_complexity_id = complexity_id;
}
}
DeviceCompexity Model
[Table("device_complexities")]
public class DeviceComplexity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Device_complexity_id { get; set; }
public string Device_complexity_name { get; set; }
public DeviceComplexity()
{
}
public DeviceComplexity(string name)
{
Device_complexity_name = name;
}
}
I now get an error in the conversion method
You'd try to cast your LINQ query result to ObservableCollection<DeviceCategoryViewModel> in separate Convert function.
Why not to directly collect your LINQ query result to ObservableCollection<DeviceCategoryViewModel>
Just use like this
var q = from cat in dc.DeviceCategories
join com in dc.DeviceComplexities on cat.Device_complexity_id equals com.Device_complexity_id
select new DeviceCategoryViewModel // <= Note This Line
{
Device_category_id = cat.Device_category_id,
Category_name = cat.Category_name,
Device_complexity_id = com.Device_complexity_id,
Device_complexity_name = com.Device_complexity_name
};
deviceCategories = new ObservableCollection<DeviceCategoryViewModel>(q);
OR if you want to get result after list then simply use q.ToList()
deviceCategories = new ObservableCollection<DeviceCategoryViewModel>(q.ToList());

Dynamic class based on string parameter

I have this:
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
public List<???prpClass???> Whatever(string prpClass)
where string prpClass can be "Blah" or "Doh".
I would like the List type to be class Blah or Doh based on what the string prpClass holds.
How can I achieve this?
EDIT:
public List<prpClass??> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result;
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result;
}
return null
}
}
you have to have a common supertype:
public interface IHaveAnId
{
int id { get;set; }
}
public class Blah : IHaveAnId
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh : IHaveAnId
{
public int id {get;set;}
public string dohh { get; set; }
public string mahh { get; set; }
}
then you can do:
public List<IHaveAnId> TheList = new List<IHaveAnId>();
and in some method:
TheList.Add(new Blah{id=1,blahh = "someValue"});
TheList.Add(new Doh{id =2, dohh = "someValue", mahh = "someotherValue"});
to iterate through the list:
foreach(IHaveAnId item in TheList)
{
Console.WriteLine("TheList contains an item with id {0}", item.id);
//item.id is allowed since you access the property of the class over the interface
}
or to iterate through all Blahs:
foreach(Blah item in TheList.OfType<Blah>())
{
Console.WriteLine("TheList contains a Blah with id {0} and blahh ='{1}'", item.id, item.blahh);
}
Edit:
the 2 methods and a int field holding the autovalue:
private int autoValue = 0;
public void AddBlah(string blahh)
{
TheList.Add(new Blah{id = autovalue++, blahh = blahh});
}
public void AddDoh(string dohh, string mahh)
{
TheList.Add(new Doh{id = autovalue++, dohh = dohh, mahh = mahh});
}
Another Edit
public List<object> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result.Cast<object>().ToList();
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result.Cast<object>.ToList();
}
return null;
}
}
in the view you then have to decide what type it is. In asp.net MVC you can use a display template and use reflection to get a good design. But then i still don't know what technology you are using.
Yet another Edit
TestClass:
public class SomeClass
{
public string Property { get; set; }
}
Repository:
public static class Repository
{
public static List<object> Whatever(string prpClass)
{
switch (prpClass)
{
case "SomeClass":
return new List<SomeClass>()
{
new SomeClass{Property = "somestring"},
new SomeClass{Property = "someOtherString"}
}.Cast<object>().ToList();
default:
return null;
}
}
}
And a controller action in mvc:
public JsonResult Test(string className)
{
return Json(Repository.Whatever("SomeClass"),JsonRequestBehavior.AllowGet);
}
then i called it with: http://localhost:56619/Home/Test?className=SomeClass
And got the result:
[{"Property":"somestring"},{"Property":"someOtherString"}]
Is this what you are trying to do?
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
class Program
{
public static List<T> Whatever<T>(int count) where T: new()
{
return Enumerable.Range(0, count).Select((i) => new T()).ToList();
}
static void Main(string[] args)
{
var list=Whatever<Doh>(100);
// list containts 100 of "Doh"
}
}

Dapper.NET filling a class in "list of class"

I am new on Dapper.NET kinda stuck on this. I am trying to fill a class which has another class from multirow result set.
# DATABASE SP >
SELECT b.BuildingId, b.BuildingName, b.Wood, b.Food, b.Stone, b.Gold FROM UserBuildings ub, Buildings b WHERE b.BuildingId = ub.BuildingId AND UserId = #UserId
# CODE >
using (IDbConnection connection = OpenConnection())
{
List<Building.Building> buildings = new List<Building.Building>();
var multi = connection.QueryMultiple<Building.Building, Resource.Resource>("UserBuildingGet", new { UserId = UserId }, commandType: CommandType.StoredProcedure).ToList();
building.Resource = multi.Read<Resource.Resource>().Single();
return building;
}
# CLASSES >
public class Building
{
private int _BuildingId;
private string _BuildingName;
private Resource.Resource _Resource;
public int BuildingId
{
get { return _BuildingId; }
set { _BuildingId = value; }
}
public string BuildingName
{
get { return _BuildingName; }
set { _BuildingName = value; }
}
public Resource.Resource Resource
{
get { return _Resource; }
set { _Resource = value; }
}
public Building(int BuildingId, string BuildingName, Resource.Resource Resource)
{
this.BuildingId = BuildingId;
this.BuildingName = BuildingName;
this.Resource = Resource;
}
}
public class Resource
{
private int _Wood;
private int _Food;
private int _Stone;
private int _Gold;
public int Wood
{
get { return _Wood; }
set { _Wood = value; }
}
public int Food
{
get { return _Food; }
set { _Food = value; }
}
public int Stone
{
get { return _Stone; }
set { _Stone = value; }
}
public int Gold
{
get { return _Gold; }
set { _Gold = value; }
}
public Resource(int Wood, int Food, int Stone, int Gold)
{
this.Wood = Wood;
this.Food = Food;
this.Stone = Stone;
this.Gold = Gold;
}
}
Your code needs to define what separates the data. Use the splitOn parameter of GridReader.Read
var buildings = new List<Building.Building>();
using (IDbConnection connection = OpenConnection())
{
using(var reader = connection.QueryMultiple("UserBuildingGet",
new { UserId = UserId },
commandType: CommandType.StoredProcedure))
{
var building = reader.Read<Building.Building,
Resource.Resource,
Building.Building>
((b, r) => { b.Resource = r; return b; }, splitOn: "Wood");
buildings.AddRange(building);
}
}
return buildings;
See: Is there a way of using MultiMapping and QueryMultiple together in Dapper?
Sample:
public class Building
{
public int BuildingId { get; set; }
public string BuildingName { get; set; }
public Resource Resource { get; set; }
public override string ToString()
{
return string.Format("Id: {0} Name: {1} Resource: {2}", BuildingId, BuildingName, Resource);
}
}
public class Resource
{
public int Wood { get; set; }
public int Food { get; set; }
public int Stone { get; set; }
public int Gold { get; set; }
public override string ToString()
{
return string.Format("Wood: {0} Food: {1} Stone {2} Gold {3}", Wood, Food, Stone, Gold);
}
}
var sql = #"SELECT 1 AS BuildingId, 'tower' AS BuildingName, 1 AS Wood, 1 AS Food, 1 AS Stone, 1 AS Gold
UNION ALL
SELECT 2 AS BuildingId, 'shed' AS BuildingName, 1 AS Wood, 1 AS Food, 1 AS Stone, 1 AS Gold";
var buildings = new List<Building>();
using(var connection = GetOpenConnection())
{
using(var reader = connection.QueryMultiple(sql))
{
var building = reader.Read<Building, Resource, Building>(
(b, r) => { b.Resource = r; return b; }, splitOn: "Wood");
buildings.AddRange(building);
}
}
foreach(var building in buildings)
{
Console.WriteLine(building);
}

Categories

Resources