How to get all the females? - c#

I would like to get the gender for calculations, for example the male and female options are in one column. I would like to get all male or all female for calculation.
I have a "computed property" which gives me list of all the items along with calculation. Here is the code:
partial void MeanFemale_Compute(ref string result)
{
// Set result to the desired field value
int totalAge = 0;
int count = 0;
foreach (InsuranceQuotation i in his.DataWorkspace.ApplicationData.InsuranceQuotations)
{
totalAge += i.mAge;
count++;
}
if (count != 0)
{
result = (totalAge / count).ToString();
}
}
How do I get to filter the gender in this "computed property".

You can use LINQ. It would look something like this:
int averageAge = this.DataWorkspace.ApplicationData.InsuranceQuotations.
Where(iq => iq.Gender == Gender.Female).
Average(iq => iq.mAge);

Could you filter with an if statement?
partial void MeanFemale_Compute(ref string result)
{
// Set result to the desired field value
int totalAge = 0;
int count = 0;
foreach (InsuranceQuotation i in this.DataWorkspace.ApplicationData.InsuranceQuotations)
{
if(i.Female == true)
{
totalAge += i.mAge;
count++;
}
}
if (count != 0)
{
result = (totalAge / count).ToString();
}
}

Hope this would help someone else for filtering the Choice List
in _InitializeDataWorkspace:
// get count of females
double fgender = (from gender in InsuranceQuotations
where gender.mGender == "Female"
select gender).Count();
//get sum of females ages
double female = InsuranceQuotations.Where(x => x.mGender == "Female").Sum(t => t.mAge);
// get count males
double mgender = (from gender in InsuranceQuotations
where gender.mGender == "Male"
select gender).Count();
//get sum of males ages
double male = InsuranceQuotations.Where(x => x.mGender == "Male").Sum(t => t.mAge);
// MeanFmale amd MeanMmale - The fields that display
MeanFmale = (female / fgender).ToString();
MeanMmale = (male / mgender).ToString();
Or
double fmale = InsuranceQuotations.Where(x => x.mGender == "Female").Average(t => t.mAge);
double mmale = InsuranceQuotations.Where(x => x.mGender == "Male").Average(t => t.mAge);
// MeanFmale amd MeanMmale - The fields that display
MeanFmale = fmale.ToString();
MeanMmale = mmale.ToString();

Related

how to calculate sum of times in a column using foreach loop ASP.NET MVC

enter image description here
suppose A is my Table and inside this table i have one column like times
inside column name times i have n number of times
Example :-1st:-02:30
2nd:-03:25
3rd:-00:45
i want output like TotalTime=06:40
i got out put using jquery but i want how to do inside a controller using foreach loop please help me
my controller code:-
[HttpPost]
public ActionResult getTimeSheetByBasit(DateTime? CurrentDate, string ActivityTime)
//obj.UserDocumentList = ThidDb.UserDocument.Where(x => x.CreatedBy == UserId).ToList();
{
VM_TimeSheet ObjVM_TimeSheet = new VM_TimeSheet();
int LoggedUser = User.KEY();
string LoggedUserName = User.UserName();
string UserEmail = User.EmailID();
DateTime TimeIn, TimeOut;
string TimeInn, TimeOuut, TotalTime;
//code add here fot adding text box time with total houres enter by user select time Sheet
using (SecurenetDB SecurenetDB = new SecurenetDB())
{
ObjVM_TimeSheet.TimesheetList = SecurenetDB.AD_TimeSheet.Where(x => DbFunctions.TruncateTime(x.ActivityDate.Value) == DbFunctions.TruncateTime(CurrentDate) && x.UserKEY == LoggedUser).ToList();
TimeIn = SecurenetDB.AD_CardPunching.Where(x => DbFunctions.TruncateTime(x.EventDate) == DbFunctions.TruncateTime(CurrentDate) && x.UserName == LoggedUserName).Select(x => x.Time_In).FirstOrDefault();
TimeOut = SecurenetDB.AD_CardPunching.Where(x => DbFunctions.TruncateTime(x.EventDate) == DbFunctions.TruncateTime(CurrentDate) && x.UserName == LoggedUserName).Select(x => x.Time_Out).FirstOrDefault();
TimeInn = TimeIn.ToString("hh:mm tt");
TimeOuut = TimeOut.ToString("hh:mm tt");
TotalTime = SecurenetDB.AD_CardPunching.Where(x => DbFunctions.TruncateTime(x.EventDate) == DbFunctions.TruncateTime(CurrentDate) && x.UserName == LoggedUserName).Select(x => x.TotalHours).FirstOrDefault();
// ObjVM_TimeSheet.TimesheetList=SecurenetDB.AD_TimeSheet.Where(x=>x.Hours== TextTime && x.UserKEY == LoggedUser).ToList();
var sum = "00:00";
foreach(var iteam in ActivityTime)
{
sum = sum + iteam;
}
}
return Json(new
{
TimeSheetData = this.RenderPartialViewToString("TimeSheetData", ObjVM_TimeSheet.TimesheetList),
TimeIn = TimeInn,
TimeOut = TimeOuut,
TotalTime = TotalTime
}, JsonRequestBehavior.AllowGet);
}
enter image description here
Use TimeSpan
string[] times = new string[] {"02:30", "03:25", "00:45"};
TimeSpan totalTime = new TimeSpan(0);
foreach (string time in times)
{
TimeSpan ts = TimeSpan.Parse(time);
totalTime += ts;
}
Console.WriteLine(totalTime.ToString(#"hh\:mm"));
Output
06:40

Get the index of item in list based on value

The scenario is for a football league table. I can order the list by match win percentage and then by goals scored to determine their position in the league. I then use this ordering to get teams position in the league table using the IndexOf function.
this.results = this.results.OrderByDescending(x => x.WinPercentage).ThenByDescending(x => x.Goals);
this.results.Foreach(x => x.Position = this.results.IndexOf(x));
The problem arises when two teams (should be joint #1) have the same match win percentage and goals scored but when getting the index one team will be assigned #1 and the other #2.
Is there a way to get the correct position?
var position = 1;
var last = result.First();
foreach(var team in results)
{
if (team.WinPercentage != last.WinPercentage || team.Goals != last.Goals)
++position;
team.Position = position;
last = team;
}
What you could do is group the items based on the win percentage and goals (if both are the same, the teams will be in the same group), then apply the same position number to every element in the same group:
this.results = this.results.OrderByDescending(x => x.WinPercentage).ThenByDescending(x => x.Goals);
var positionGroups = this.results.GroupBy(x => new { WinPercentage = x.WinPercentage, Goals = x.Goals });
int position = 1;
foreach (var positionGroup in positionGroups)
{
foreach (var team in positionGroup)
{
team.Position = position;
}
position++;
}
The code below code will work for you
this.results = this.results.OrderByDescending(x => x.WinPercentage).ThenByDescending(x => x.Goals);
this.results.Foreach(x =>
{
int index = this.results.FindIndex(y => y.Goals == x.Goals && y.WinPercentage == x.WinPercentage);
x.Position = index > 0 ? this.results[index - 1].Position + 1 : 0;
});
Here's my solution
Define a class:
public class ABC
{
public int A { get; set; }
public int B { get; set; }
public int R { get; set; }
}
Constructing numerical:
List<ABC> list = new List<ABC>();
for (var i = 0; i < 100; i++)
{
list.Add(new ABC()
{
A = i,
B = i > 50 && i < 70 ? i + 20 : i + 1
});
}
Ranking and print the values:
var result = list.OrderByDescending(d => d.B)
.GroupBy(d => d.B)
.SelectMany((g, `i`) => g.Select(e => new ABC()
{
A = e.A,
B = e.B,
R = i + 1
})).ToList();
foreach (var t in result)
{
Console.WriteLine(JsonConvert.SerializeObject(t));
}
Console.ReadLine();
the result:

Randomly Selected Data from Database with Constraints

I have created a MySQL Database with a vast number of products and their cost. I utilize EF6 to wrap the database.
Based on the given input, I need to generate at random, a correct selection that meets the described criteria.
For example:
10 Items, Total Value $25
I am at a loss as how to properly go about iterating through the database to produce the required results.
What I am currently doing seems terribly inefficent:
using (var db = new Database())
{
var packageSelected = false;
var random = new Random();
var minItemId = (from d in db.products select d.id).Min();
var maxItemId = (from d in db.products select d.id).Max();
var timer = new Stopwatch();
timer.Start();
Console.WriteLine("Trying to make package...");
while (!packageSelected)
{
var currentItems = new List<int>();
for (var i = 0; i <= 9; i++)
{
var randomItem = random.Next(minItemId, maxItemId);
currentItems.Add(randomItem);
}
decimal? packageValue = 0;
currentItems.ForEach(o =>
{
var firstOrDefault = db.products.FirstOrDefault(s => s.id == o);
if (firstOrDefault != null)
{
var value = firstOrDefault.MSRP;
packageValue += value;
}
});
if (!(packageValue >= 25) || !(packageValue <= 26)) continue;
packageSelected = true;
timer.Stop();
Console.WriteLine("Took {0} seconds.", timer.Elapsed.TotalSeconds);
currentItems.ForEach(o =>
{
var firstOrDefault = db.products.FirstOrDefault(s => s.id == o);
if (firstOrDefault != null)
Console.WriteLine("Item: {0} - Price: ${1}", firstOrDefault.DESCRIPTION,
firstOrDefault.MSRP);
});
}
}
What about something like this:
public virtual TEntity GetRandom()
{
return DBSet.OrderBy(r => Guid.NewGuid()).Take(1).First();
}
public List<TEntity> Random(int amount, int maxprice)
{
var list = new List<TEntity>();
var tempPrice = 0;
for (int i = 0 ; i < amount; i++)
{
var element = GetRandom();
tempPrice += element.Price;
if (tempPrice > maxprice)
{
return list;
}
list.Add(element);
}
return list;
}
hope this helps
EDIT: If the maxprice is reached before the required amount of elements, the for-loop will stop and you won't get the full amount of elements.

Increment in LINQ Query

Hello I have the following code which returns me List of type Listitem. I want to increase the value by one for every ListItem Selected.
public static List<System.Web.UI.WebControls.ListItem> GetMyCompassTUTListContent(List<int> ContentID, Int32 CountryID)
{
int Counter = 0;
List<System.Web.UI.WebControls.ListItem> litems = new List<System.Web.UI.WebControls.ListItem>();
using (DbDataContext objContext = new DbDataContext())
{
if (CountryID == (int)MyCompassBLL.Constants.Country.Australia)
{
litems = objContext.Contents.Where(x => ContentID.Contains(x.ID)).Select(x => new System.Web.UI.WebControls.ListItem { Text = x.Text, y = (y + 1) }).ToList();
}
else
{
litems = objContext.ContentCountries.Where(x => ContentID.Contains(x.ContentID) && x.CountryID == CountryID).Select(x => new System.Web.UI.WebControls.ListItem { Text = x.Text, Value = (Counter + 1).ToString() }).ToList();
}
}
return litems;
}
Please help me in this. I am not able to that since I am not able to find the way of how to reassign value to variable counter after increment.
Thanks in advance
There is an overload of Select that also provides the index of the current item. You can use that. However, most DB query providers don't support it, so you'll need to do your DB query, then ensure that the Enumerable overload of Select is called to add the index:
public static List<ListItem> GetMyCompassTUTListContent(
List<int> ContentID, Int32 CountryID)
{
//Note this is IEnumerable, not IQueryable, this is important.
IEnumerable<string> query;
using (DbDataContext objContext = new DbDataContext())
{
if (CountryID == (int)MyCompassBLL.Constants.Country.Australia)
{
query = objContext.Contents.Where(x => ContentID.Contains(x.ID))
.Select(x => x.Text);
}
else
{
query = objContext.ContentCountries
.Where(x => ContentID.Contains(x.ContentID)
&& x.CountryID == CountryID)
.Select(x => x.Text);
}
return query.Select((text, index) => new ListItem
{
Text = text,
Value = (index + 1).ToString(),
})
.ToList();
}
}
Use ++Counter instead of ( Counter + 1)
[UPDATE]
try to increment your Counter before put it into the Select():
else
{
Counter++;
litems = objContext.ContentCountries.Where(x => ContentID.Contains(x.ContentID) && x.CountryID == CountryID).Select(x => new System.Web.UI.WebControls.ListItem { Text = x.Text, Value = Counter.ToString() }).ToList();
}

Remove from List<> duplicated items and record duplicated quantity

I have a List<Item>. Item has properties Id,Name and Amount. There are duplicated items in this list. I need to get a new List<Item> which contains only non-duplicated Items and in Item's Amount should be the quantity of how many times it duplicated in first List<Item>. I tried something like
for (int i = 0; i < list.Count; i++)
{
for (int j = 0; j < list.Count; j++)
{
if (list[i].Name == list[j].Name)
{
list.Remove(prod.Components[j]);
list[i].Amount++;
}
}
}
but there are some problems in this loop. My brains are overheated. Please, help.
A simple LINQ query can get you the unique items along with the number of times they appear:
var distinct = list.GroupBy(o => o.Name)
.Select(g => new { Count = g.Count(), Item = g.First() })
.ToList();
Then you can modify each item's Amount to the count of duplicates:
foreach (var row in distinct)
{
row.Item.Amount = row.Count;
}
And finally get back a List<Item> that contains no duplicates and has the correct amounts:
var uniqueItems = distinct.Select(r => r.Item).ToList();
Important: The code above assumes that "duplicate" items are indistinguishable from each other, but nothing else (e.g. it doesn't need Item to have a default constructor). Depending on the particulars it may be possible to write it in an even shorter form.
Additionally, the Amount property looks strange here. Since duplicates do not warrant summation of their amounts, what's the purpose of Item.Amount? I would assume that duplicate items with amount of 2 should result in one item with an amount of 4, but your code does not do that (and mine follows that lead).
Off the top of my head (haven't tested it):
list.GroupBy(x => x.Name)
.Select(x => new Item {
Name = x.Key,
Amount = x.Count()
})
.ToList();
You haven't specified what happens to the Ids, so I've left ignored them.
(Note this creates a new list, rather than modifying the original).
Try something like that:
var groups = from item in items
group item by item.Property
into grouped
select grouped;
var distinct = from g in groups
let item = g.First()
let amount = g.Count()
select new Item {Property = item.Property, Amount = amount};
After that distinct contains IEnumerable<Item> with their amount from original items list.
foreach(var item in list)
{
if(list.Count(e=>e.Id == item.Id && e.Name == item.Name)!=1)
{
list.Remove(item);
}
}
Assuming that you determine duplicates by the first two properties ID and Name.
You can implement an IEqualityComparer<Item> and use that for Enumerable.GroupBy:
var itemAmounts = items.GroupBy(i => i, new Item())
.Select(g => new Item {
ID = g.First().ID,
Name = g.First().Name,
Amount = g.Count()
});
Here's your Item class with a meaningful implementation of IEqualityComparer<Item>:
class Item : IEqualityComparer<Item>
{
public int ID;
public string Name;
public int Amount;
public bool Equals(Item x, Item y)
{
if (x == null || y == null) return false;
bool equals = x.ID == y.ID && x.Name == y.Name;
return equals;
}
public int GetHashCode(Item obj)
{
if (obj == null) return int.MinValue;
int hash = 19;
hash = hash + obj.ID.GetHashCode();
hash = hash + obj.Name.GetHashCode();
return hash;
}
}
You could also override Equals and GetHasdhCode from object, then you don't need a custom comparer at all in GroupBy:
var itemAmounts = items.GroupBy(i => i)
.Select(g => new Item {
ID = g.First().ID,
Name = g.First().Name,
Amount = g.Count()
});
You can use above already available methods:
public override bool Equals(object obj)
{
Item item2 = obj as Item;
if (item2 == null)
return false;
else
return Equals(this, item2);
}
public override int GetHashCode()
{
return GetHashCode(this);
}

Categories

Resources