Pass through list by period - c#

I have a List<Items> for example 365 elements
public DateTime DayD { get; set; }
public double Day { get; set; }
public double Week { get; set; }
public double Month { get; set; }
How to pass through the list by period 30 day - mean for each element select next 30 element.

I would use LINQ with a yield return, something like :
static IEnumerable<List<Item>> GetXMany(int pageSize)
{
for (int i = 0; i < items.Count(); i+=pageSize)
{
yield return items.Skip(i).Take(pageSize).ToList();
}
}
and loop through it with :
foreach (List<Item> items in GetXMany(30))
{
}

Related

Iterate over Entity Framework object properties

I have a table "StaffMembers" that have columns indicating the number of days worked in a month, the properties in the model are as follows:
public class StaffMember
{
public int Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int Phone { get; set; }
public string Email { get; set; }
public string BirthDate { get; set; }
public int OctDays { get; set; }
public int NovDays { get; set; }
public int DecDays { get; set; }
public int JanDays { get; set; }
public int FebDays { get; set; }
public int MarDays { get; set; }
public int AprDays { get; set; }
}
now I retrieve the specific staffMember using linq:
var staffMember = (from b in db.StaffMembers
where b.Id == Id
select b).FirstOrDefault();
what I want to do is to loop over the months properties in staffMember and add all the worked days together to get total working days in the year.
for example if he worked 10 days in oct and 20 days in dec and 30 days in jan, I want a way to iterate over the months and sum the days.
You can do it by iterating over object properties and apply your condition on it.
static void Main(string[] args)
{
var staffA = new StaffMember();
int totalWorkDays = 0;
staffA.AprDays = 5;
staffA.FebDays = 7;
foreach (var item in staffA.GetType().GetProperties())
{
if (item.Name.EndsWith("Days"))
{
totalWorkDays += (int)item.GetValue(staffA)!;
}
}
Console.WriteLine(totalWorkDays);
}
this snippet prints ( 5 + 7 ) => 12
You can use reflection to iterate over the properties, but I do not recommend this because you have to point anyway which properties you want to take into consideration. That's because you have multiple integer properties like Id and Phone so you cannot indicate in the loop that you want to sum integer properties, you have to show explicitly that you want to sum OctDays etc. or write some algorithms that indicates that the current property is responsible for the month. So the best way (and in my opinion simplier than reflection way) would be just to get each of the month explicit and sum like this:
var sum = staffMember.OctDays + staffMember.NovDays + staffMember.DecDays + staffMember.JanDays + staffMember.FebDays + staffMember.MarDays + staffMember.AprDays

Empty string comparison is failing

Currently writing a simple reservation. Right now I have a multidimensional string array that holds the passengers name and I am trying to iterate through that array and see whether there are any open seats so I know whether or not to add them to a waiting list.
// Check how many seats are taken
for (int i = 0; i <= nameArray.GetUpperBound(0); i++)
{
for (int j = 0; j <= nameArray.GetUpperBound(1); j++)
{
if (nameArray[i, j] == "")
{
seatsFilled--;
}
else
{
seatsFilled++;
}
}
}
For some reason when I debug, I notice that this line
if (nameArray[i, j] == "")
Doesn't do anything at all and gets skipped over despite there being no names in the array. I cannot for the life of me figure out why. Any suggestions?
One of the reason i can see is the comparison may have the whitespace. Try this
if(string.IsNullOrWhiteSpace(nameArray[i, j]))
I would do something like this:
First I would create some interfaces and models that would define the structure of the seat. Make sure to account for seat restrictions.
public interface ISeat
{
int RowNumber { get; }
string SeatLetter { get; }
PassangerModel Passenger { get; }
}
We want to allow some of the seats to be restricted based on passenger age and height. Hard coding that into each seat is nasty so instead I created a SeatRestriction class that has a predicate in it. This predicate will take the passenger model in and return a result. So for example you could create a SeatRestriction that checked a passengers height or age to make sure they can open emergency doors.
public class SeatRestriction
{
public Predicate<PassangerModel> Restriction { get; private set; }
public SeatRestriction(Predicate<PassangerModel> restriction)
{
Restriction = restriction;
}
}
The passenger model can actually be much more verbose than this. I'm assuming here no dietary needs. Maybe this is a reservation system for Spirit Airlines.
public class PassangerModel
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string CreditCardName { get; set; }
public string CreditCardNumber { get; set; }
public string CreditCardExpiration { get; set; }
public string CreditCardSecurityPin { get; set; }
}
Next We come to our seat class. This class allows us to see if a passenger is assigned to the seat. Take note that it also asserts prior to adding the passenger to the seat if the passenger meets the restrictions, if any.
public interface IRestrictedSeat
{
List<SeatRestriction> Restrictions { get; }
bool AssertQualifiedPassenger(PassangerModel passenger);
}
public class Seat : ISeat, IRestrictedSeat
{
public bool IsSeatReserved { get { return Passenger != null; } }
public int RowNumber { get; private set; }
public string SeatLetter { get; private set; }
public PassangerModel Passenger { get; private set; }
public List<SeatRestriction> Restrictions { get; private set; }
public Seat(int rowNumber, string seatLetter)
{
Restrictions = new List<SeatRestriction>();
RowNumber = rowNumber;
SeatLetter = seatLetter;
}
public bool TryAddPassenger(PassangerModel passanger)
{
if (AssertQualifiedPassenger(passanger))
{
Passenger = passenger;
return true;
}
else
{
return false;
}
}
public bool AssertQualifiedPassenger(PassangerModel passenger)
{
foreach(SeatRestriction restriction in Restrictions)
{
if (!restriction.Restriction(passenger))
{
return false;
}
}
return true;
}
}
Finally we get to the row. Our row knows how manys seats it has and what its number is. You should be able to add seats to it and then call GetAvailableSeats to get the seats that are left in this row.
public class SeatRow
{
public int TotalSeats { get; private set; }
public int RowNumber { get; private set; }
public List<Seat> Seats { get; private set; }
public SeatRow(int seatsInRow, int rowNumber)
{
TotalSeats = seatsInRow;
RowNumber = rowNumber;
}
public bool TryAddSeatToRow(Seat seat)
{
if(Seats.Count <= TotalSeats && seat.RowNumber == RowNumber)
{
Seats.Add(seat);
return true;
}
else
{
return false;
}
}
public IEnumerable<Seat> GetAvailableSeats()
{
return Seats.Where(seat => seat.IsSeatReserved == false);
}
}
The long and short of this answer is there's a million ways to solve CIS problems and to not rely on stack overflow while you're in school/learning. Good luck and welcome to the club :-)
if (nameArray[i, j] == "")
Doesn't do anything at all and gets skipped over despite there being no names in the array.
That line is inside a loop that iterates through the items in the array. If the array is empty then this will never get executed.

Retrieve values from JSON

I am retrieving values from JSON and want to compare that. but I am getting Index Out of Range Exception on:
string email = contactdata.data[0].email[i].value;
Code:
int length = contactdata.data.Length;
for (int i = 0; i <= length; i++)
{
string email = contactdata.data[0].email[i].value;
if (contactemail == email)
{
counter++;
flag = 1;
break;
}
}
JSON Class:
public class Rootobject
{
public bool success { get; set; }
public Datum[] data { get; set; }
public Additional_Data additional_data { get; set; }
}
public class Additional_Data
{
public Pagination pagination { get; set; }
}
public class Pagination
{
public int start { get; set; }
public int limit { get; set; }
public bool more_items_in_collection { get; set; }
}
public class Datum
{
public int id { get; set; }
public Email[] email { get; set; }
}
public class Email
{
public string label { get; set; }
public string value { get; set; }
public bool primary { get; set; }
}
change the line
int length = contactdata.data.Length;
to
int length = contactdata.data[0].email.Length;
and change the condition in the for loop from i <= length to i < length.
Change this
for (int i = 0; i <= length; i++)
with
for (int i = 0; i < length; i++)
index start alwais from 0
Your iteration variable is on the contactdata.datanot on email, thus your i variable is on these indexes.
As I mentioned in a comment, using a nested for loop over data and ALSO over email will ensure you actually have an email you can look at!
The index out of range error means that you're trying to access an item in an array that doesn't exist.
I did not test the following code, but I used really explicit variable names in the loop to show you what I'm trying to count, and how I can only access something in an array if I know that it actually exists:
//first get the length of data
var dataLength = contactdata.data.Length;
//now loop through it
for (var dataCounter = 0; dataCounter < dataLength; dataCounter++){
//next get the length of email - is there even an email available?
var emailLength = contactdata.data[dataCounter].email.Length;
for (var emailCounter = 0; emailCounter < emailLength; emailCounter ++){
//now you can access the email and work with it.
if (contactemail == contactdata.data[dataCounter].email[emailCounter]){
// here do your code
}
}
}

FlatBuffers KeyValuePair data type and schema definition

I have an object that I need to send over the network using TCP. I had this working fine, but I have now expanded on my implementation and am having trouble working out how to define my FlatBuffer schema.
The object to be sent is this:
public class Prediction
{
public PredictionMethod PredictionMethod { get; set; }
public NGramPrediction NGramPrediction { get; set; }
public DistancePrediction DistancePrediction { get; set; }
public int NGramOrder { get; set; }
}
PredictionMethod is an enum:
public enum PredictionMethod
{
Distance = 1,
NGram = 2,
}
NGramPrediction looks like this:
public class NGramPrediction
{
public KeyValuePair<char, int> Gram { get; set; }
public double Probability { get; set; }
public string Pattern { get; set; }
private int Total { get; set; }
private int Order { get; set; }
public NGramPrediction(Gram gram)
{
Total = gram.Total();
var orderedKeyPosibilities = gram.Posibilities.OrderByDescending(x => x.Value);
Gram = orderedKeyPosibilities.First();
Pattern = gram.Pattern;
Probability = (double)Gram.Value / Total;
Order = Pattern.Length;
}
}
Gram looks like this:
public class Gram
{
public string Pattern { get; set; }
public Dictionary<char, int> Posibilities { get; set; }
public Gram(List<char> posibilities, int initialValue = 0)
{
Posibilities = new Dictionary<char, int>();
foreach (var posibility in posibilities)
{
Posibilities.Add(posibility, initialValue);
}
}
public int Total()
{
var keys = Posibilities.Keys;
var total = 0;
foreach (var key in keys)
{
var value = Posibilities[key];
total += value;
}
return total;
// return keys.Sum(key => Posibilities[key]);
}
}
DistancePrediction looks like this:
public class DistancePrediction
{
public IIRVector3 Velocity { get; set; }
public float DeltaTime { get; set; }
public IIRVector3 Position { get; set; }
}
and finally, IIRVector3 looks like this:
public class IIRVector3
{
public IIRVector3()
{
X = 0;
Y = 0;
Z = 0;
}
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
}
I'm trying to define my schema for FlatBuffers:
enum FBPredictionMethod
{
Distance = 1,
NGram = 2
}
struct FBIIRVector3
{
X:float;
Y:float;
Z:float;
}
table FBDistancePrediction
{
Velocity:FBIIRVector3;
DeltaTime:float;
Position:FBIIRVector3;
}
table FBGram
{
Pattern:string;
Possibilities: ????
}
table FBNGramPrediction
{
Gram: ????
Probability:float;
Pattern:string;
Total:short;
Order:short;
}
table FBPrediction
{
PredictionMethod:FBPredictionMethod;
NGramPrediction:FBNGramPrediction;
DistancePrediction:FBDistancePrediction;
NGramOrder:short;
}
root_type FlatServerToClientMessage;
I think everything looks correct, but I have no idea what to do for the dictionaries...
FBGram.Possibilities should be a Dictionary<char, int> and FBGram should be KeyValuePair<char, int>.
Note: Gram's constructor takes a List<char> and an int as parameters, while the constructor for NGramPrediction takes a Gram as a parameter.
Could someone help me with my schema, please?
The KeyValuePair should be easy.. either just store them as two seperate fields, or use a struct KeyValuePair { key:byte; value:int; }
The Dictionary could be stored as Possibilities:[KeyValuePair] (using that same struct). If you wanted to save space if Possibilities can be large, then PossibilityKeys:[byte] and PossibilityValues:[int] will be a little bit more compact, but harder to read/write.

searching a date list

I have a collection list which contains the following fields
Date1
Xvalue
Yvalue
I want to seach within this list against another date list. For every date in the second list I want to get records starting between this minimum date and the next date is which (30 minutes to the minium date).
foreach (var item in selectedDates.Where(x => x.Checked))
{
// item.minDate is my starting date
// I want all records between item.minDate and 30 minutes added to it)
var t = lf.ReplicateBlocks.FindAll(o=> o.minimumCompletionDate >= item.
}
**UPDATE**
public class ReplicateBlock
{
public int ReplicateId { get; set; }
public string AssayNumber { get; set; }
public DateTime InitiationDate { get; set; }
public DateTime InitiationTime { get; set; }
public DateTime minimumCompletionDate { get; set; }
public DateTime minimumCompletionTime { get; set; }
public string correctedCount { get; set; }
public string moduleName { get; set; }
public string exception { get; set; }
}
public class RunLogEntryDatesDisplay
{
public DateTime runDate { get; set; }
public String DateRange { get; set; }
public bool Checked { get; set; }
public string MinimumReplicateId { get; set; }
}
The final output I am looking for is a revised Replicate Block list. RunLogEntryDatesDisplay is a checkbox list posted from the view. In this list I look at the checked date which is runDate and starting from the first selection I add 30 minutes to it and find all records in ReplicateBlock List in between and the edges. I will do the same for every selected date in the checbox list and in the end will have a final/filtered ReplicateBlockLisr based on users selections(checked item).
You could loop through the dates and populate a result list:
List<ReplicateBlock> blocks = new List<ReplicateBlock>();
foreach (var item in selectedDates.Where(x => x.Checked))
{
var t = lf.ReplicateBlocks.Where(o=>
o.minimumCompletionDate >= item.minDate &&
o.minimumCompletionDate <= item.minDate.AddMinutes(30));
blocks.AddRange(t);
}
You could also do it in one query:
var query = from d in selectedDates
from o in lf.ReplicateBlocks
where d.Checked &&
o.minimumCompletionDate >= d.minDate &&
o.minimumCompletionDate <= d.minDate.AddMinutes(30))
select o;

Categories