class user
{
public string userID { get; set; }
public string groupID { get; set; }
public int individualCredit { get; set; }
public int groupCredit { get; set; }
}
I have a list like this
List<user> listUsers = new List<user>();
I want to group users with same groupID.
Calculate groupCredit by adding the individualcredit s of each member in group and by dividing it by the number of group members.
Finally I want to assign each user with their groupCredit.
There are groups with three to five members.
How to do that?
Here's what I have tried.
var groupedUsers = from users in listUsers
where users.groupID != ""
group users by users.groupID into grouphold
select grouphold ;
Here's what I don't know.
How to search for the same groupID? In what I have tried I check for all Items groupID is blank.
Althought I agree with Sahil's comment, here is a starting point...
You can use LINQ, something like this:
List<user> listUsers = new List<user>();
public int groupUsersbyID(int _groupID)
{
var ListOfUsers = (from g in listUsers where g.groupID == _groupID select g).ToList();
var count = ListOfUsers.Count();
var totalCreditforGroup = 0;
var GroupCredit = 0;
foreach (var indidCredit in ListOfUsers)
{
totalCreditforGroup = totalCreditforGroup + indidCredit.individualCredit;
GroupCredit = totalCreditforGroup / count;
}
return GroupCredit;
}
public int returnGroupID(int userId)
{
var GroupIDforUser = (from i in listUsers where i.userID == userId select i.groupID).FirstOrDefault();
return GroupIDforUser;
}
public class user
{
public int userID { get; set; }
public int groupID { get; set; }
public int individualCredit { get; set; }
public int groupCredit { get; set; }
}
Related
I have a model with list items.
public class Semester{
public int Id { get; set; }
public List<SemesterParent> Parents { get; set; }
}
public class SemesterParent{
public int Id { get; set; }
public int SemesterId { get; set; }
public int ParentId { get; set; }
}
I have a list<int> of parentids. I want to get semester list that Parents in parentids list.
For example
Semester{1,{}}
Semester{2,{}}
Semester{3,{1,2}}
Semester{4,{1}}
Semester{5,{2,4}}
When I have ParentIdes {1,2} the result is:
Semester{3,{1,2}}
Semester{4,{1}}
I use this code.
var parentIds =
await _semesterTermStudentService.Select(m => m.IsAccept && m.StudentId == student.Id);
var semester=await _semesterService.FindAsync(m=>
m.Parents.Any(y => parentIds.Contains(y.ParentId)));
You can do as below. Here is the working code
List<Semester> s = new List<Semester>();
var parentIds = new List<int> { 1, 2 };
var result = s.Where(x => x.Parents != null && x.Parents.Any() && x.Parents.All(y => parentIds.Contains(y.Id))).ToList();
I am having a class like this.
public class CameraModel
{
public int JobId { get; set; }
public int ViewId { get; set; }
public Guid ViewGuid { get; set; }
public string Name { get; set; }
public int ViewNum { get; set; }
public int LayoutID { get; set; }
public List<CameraViewItemModel> CameraViewItems { get; set; }
}
The CameraViewItemModel class is like this:
public class CameraViewItemModel
{
public int JobID { get; set; }
public Guid ViewGuid { get; set; }
public int ViewID { get; set; }
public int CamNum { get; set; }
public Guid ChannelGuid { get; set; }
public string Name { get; set; }
public ActionType Action { get; set; }
}
Now, I am assigning the list of CameraViewItemModel like this:
// get all the cameramodel's
cameraModels = _unitOfWork.Context.CameraViews.Where(m => m.JobId == siteId)
.Select(m => new CameraModel
{
JobId = m.JobId,
ViewId = m.ViewId,
ViewGuid = m.ViewGuid,
Name = m.Name,
ViewNum = m.ViewNum,
LayoutID = m.LayoutId
}).ToList();
// get all the cameraviewitemmodels
cameraViewItemModels =
(from cameraView in _unitOfWork.Repository<CameraViews>().Get(x => x.JobId == siteId).Result
join cameraViewItem in _unitOfWork.Repository<CameraViewItems>().Get(x => x.JobId == siteId)
.Result on cameraView.ViewId equals cameraViewItem.ViewId into CameraViewItemResults
from cameraViewItemResult in CameraViewItemResults.DefaultIfEmpty()
join cameraChannel in _unitOfWork.Repository<CameraChannels>().Get(x => x.JobId == siteId)
.Result on (cameraViewItemResult == null ? new Guid() : cameraViewItemResult.ChannelGuid) equals cameraChannel.ChannelGuid into CameraChannelResults
from cameraChannelResult in CameraChannelResults.DefaultIfEmpty()
select new CameraViewItemModel
{
JobID = cameraView.JobId,
ViewID = cameraView.ViewId,
ViewGuid = cameraView.ViewGuid,
CamNum = cameraViewItemResult.CamNum,
ChannelGuid = cameraChannelResult.ChannelGuid,
Name = cameraChannelResult.Name
}).ToList();
// then do a 'join' on JobId, ViewId and ViewGuid and assign the list of cameraviewitemmodels to cameraModels.
foreach (var cameraModel in cameraModels)
{
cameraModel.CameraViewItems = (from cameraViewItem in cameraViewItemModels
where cameraModel.JobId == cameraViewItem.JobID
&& cameraModel.ViewId == cameraViewItem.ViewID
&& cameraModel.ViewGuid == cameraViewItem.ViewGuid
select cameraViewItem).ToList();
}
return cameraModels;
There are three tables in database:
CameraViews, CameraViewItems, CameraChannels.
CameraViews is the main table. It is left joined with CameraViewItems and CameraChannels to get the desired result. There may not be any data in CameraViewItems and CameraChannels for a corresponding CameraView.
Is it possible to assign the list of CameraViewItemModels to CameraModels in a single linq statement.
Here is a simple way to add values to a sub list, dunno if this is what you mean. You can keep selecting sub lists if that is necessary.
var parent_lst = new List<List<string>>(); // Root/parent list that contains the other lists
var sub_lst = new List<string>(); // Sub list with values
var selected_parent_lst = parent_lst[0]; // Here I select sub list, in this case by list index
selected_parent_lst.Add("My new value"); // And here I add the new value
I have a list of users which each user has some favorite products. so each user has a list of favorite products.
in a search panel i want to check some products and as a search result I want to return list of users that at least has one of those checked product. at least one. but not users that didn't check any of those products.
public class User
{
public long Id { get; set; }
public string Name { get; set; }
public List<UserProduct> UserProducts { get; set; }
public User()
{
}
public User(long id,string name,List<long> productIds)
{
Id = id;
Name = name;
UserProducts = productIds.Select(x => new UserProduct(id, x)).ToList();
}
}
public class Products
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public Products()
{
}
public Products(int productId,string name)
{
ProductId = productId;
ProductName = name;
}
}
public class UserProduct
{
public int Id { get; set; }
public long UserId { get; set; }
public long ProductId { get; set; }
public UserProduct()
{
}
public UserProduct(long userId,long productId)
{
ProductId = productId;
UserId = userId;
}
}
public class SearchDto
{
public List<long> SearchProductIds { get; set; }
}
public class Main
{
public void FillUsers()
{
List<Products> products=new List<Products>()
{
new Products(1,"a"),
new Products(2,"b"),
new Products(3,"c"),
new Products(4,"d"),
new Products(5,"e"),
new Products(6,"f"),
new Products(7,"g"),
};
List<User> users=new List<User>()
{
new User(1,"jack",new List<long>(){1} ),
new User(2,"Mary",new List<long>(){1,4} ),
new User(3,"Sam",new List<long>(){5} ),
new User(4,"Sara",new List<long>(){7,1,2} ),
};
SearchDto dto=new SearchDto()
{
SearchProductIds = new List<long> { 1,4}
};
//Here as search dto :I want to get Jack,Mary and Sara beacause they have 1 or 4 in their products
}
}
Lets say you have a list of IDs of the products that you selected(selectedProductIdList)
I am assuming that your
User Model looks like this
public string Username {get; set;}
public string FirstName {get; set;}
//....
//more User data
//....
public List<Product> FavouriteProduct {get; set;}
Your user search result would be
var userList = listOfUsers.Where(u => u.FavouriteProduct.Where(p => selectedProductIdList.Contains(p.Id)));
Assuming all the lists are in memory, in case of database modify code accordingly.
var result= (from p1 in SearchDtoList
join p2 in UserProductList
on p1 equals p2.ProductId
join u in UserList
on p2.UserId equals u.Id
select u).ToList();
If SearchPanelDto.SelectedProductsList returns list of Ids then
Var searchedProductsIds = SearchPanelDto.SelectedProductsList;
var userList = listOfUsers.Where(m =>
searchedProductsIds.Any(x=> m.IntrestetProducts.Select(t => t.ProductId).Any(z => x.Equals(z))));
else if SearchPanelDto.SelectedProductsList return list of object which contains Id
//Get selected productIds from search panel
Var searchedProductsIds = SearchPanelDto.SelectedProductsList.select(m=>m.ProductId).ToList();
var userList = listOfUsers.Where(m =>
searchedProductsIds.Any(x=> m.IntrestetProducts.Select(t => t.ProductId).Any(z => x.Equals(z))));
How do I filter an item from a list based on two different columns one being a number(smallest number) using LINQ C#?
public class Line
{
public int Id { get; set; }
public List<LineItem> LineItems { get; set; }
public Line()
{
LineItems = new List<LineItem> {
new LineItem{Num = 1, Name="i", Qty = 0, Active = false},
new LineItem{Num = 2, Name="j", Qty = 2,Active = false},
new LineItem{Num = 3, Name="k", Qty = 3,Active = false},
};
}
}
public class LineItem
{
public int Num { get; set; }
public string Name { get; set; }
public int Qty { get; set; }
public bool Active { get; set; }
}
I want to filter this list and get a LineItem based on Qty = 0 and smallest num value.
Try filtering by Qty == 0, sorting according to Num and keep the first one:
var lineItem = LineItems.Where(l => l.Qty == 0).OrderBy(l => l.Num).FirstOrDefault();
or just keep the first that Qty equals to 0 and Num equals to minimum possible:
var minNum = LineItems.Where(l => l.Qty == 0).Min(l => l.Num);
var lineItem = LineItems.FirstOrDefault(l => l.Qty == 0 && l.Num == minNum);
You could try to get the min value for Qty is 0 and order by Num in ascending mode, then taking the first item. For sample:
var item = LineItems.Where(x => x.Qty == 0).OrderBy(x => x.Num).First();
If you have your LineItem class implement IComparable<T>, then you can do something like this:
public class LineItem : IComparable<LineItem>
{
public int Num { get; set; }
public string Name { get; set; }
public int Qty { get; set; }
public bool Active { get; set; }
public int CompareTo(LineItem other)
{
if (other.Num > this.Num)
return -1;
else if (other.Num == this.Num)
return 0;
else
return 1;
}
}
then
var item = l.LineItems.Where(p => p.Qty == 0).Min();
I have following LINQ query:
var LINQFilter = (from Cash in _DataTable_Cash.AsEnumerable()
join CashOpeningsAssignments in _DataTable_CashOpeningsAssignments.AsEnumerable().Where(a => (a.Field<Int32>("cashopeningassignmentstatus_id") == 1 || a.Field<Int32>("cashopeningassignmentstatus_id") == 2))
on Cash.Field<Int32>("cash_id") equals CashOpeningsAssignments.Field<Int32>("cash_id") into into_cashopeningsassignments
from CashOpeningsAssignments in into_cashopeningsassignments.DefaultIfEmpty()
join Users in _DataTable_Users.AsEnumerable()
on CashOpeningsAssignments.Field<Int32>("user_id") equals Users.Field<Int32>("user_id") into into_users
from Users in into_users.DefaultIfEmpty()
select new
{
cash_id = Cash.Field<Int32>("cash_id"),
cellar_name = Cellars.Field<String>("cellar_name"),
cash_name = Cash.Field<String>("cash_name"),
cashstatus_name = CashStatus.Field<String>("cashstatus_name"),
user_name = (Users == null ? "[No Data]" : Users.Field<String>("user_firstname") + (Char)32 + Users.Field<String>("user_lastname")),
cashtransaction_amount = (Cash.Field<Int32>("cashstatus_id") == 2 ? 0.00 : 150.00)
});
I have problems showing the result because this Field returns null: CashOpeningsAssignments.Field<Int32>("user_id") when CashOpeningsAssignments is Empty.
I tried moving the .DefaultIfEmpty() into users but still not working, Any idea how i can solve this?
Answer
Use the overload of DefaultIfEmpty to create an empty item.
E.g.
into_cashopeningsassignments
.DefaultIfEmpty(new CashOpeningsAssignments())
Running Code
The code reflects what you're trying to do, even though I took some liberties with it. For instance, I used List<T> instead of DataTable, because I did not figure out how to use Field<T>(string name) in a DotNetFiddle.
It's live here: https://dotnetfiddle.net/YaAc6D
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var query =
from Cash
in _DataTable_Cash.AsEnumerable()
join CashOpeningsAssignments
in _DataTable_CashOpeningsAssignments.AsEnumerable()
.Where(a =>
(a.cashopeningassignmentstatus_id == 1 ||
a.cashopeningassignmentstatus_id == 2))
on Cash.cash_id
equals CashOpeningsAssignments.cash_id
into into_cashopeningsassignments
from CashOpeningsAssignments
in into_cashopeningsassignments.DefaultIfEmpty(new CashOpeningsAssignments())
join Users
in _DataTable_Users.AsEnumerable()
on CashOpeningsAssignments.user_id
equals Users.user_id
into into_users
from Users
in into_users.DefaultIfEmpty()
select new
{
cash_id = Cash.cash_id,
// cellar_name = Cellars.cellar_name,
cash_name = Cash.cash_name,
// cashstatus_name = CashStatus.cashstatus_name,
user_name = (Users == null ? "[No Data]" : Users.user_firstname + (Char)32 + Users.user_lastname),
cashtransaction_amount = (Cash.cashstatus_id == 2 ? 0.00 : 150.00)
};
foreach(var result in query)
{
Console.WriteLine(result);
}
}
public static List<Cash> _DataTable_Cash =
new List<Cash> { new Cash() };
public static List<Cellars> _DataTable_Cellars =
new List<Cellars> { new Cellars() };
public static List<CashStatus> _DataTable_CashStatus =
new List<CashStatus> { new CashStatus() };
public static List<CashOpeningsAssignments> _DataTable_CashOpeningsAssignments =
new List<CashOpeningsAssignments> { };
public static List<Users> _DataTable_Users =
new List<Users>() { new Users() };
}
public class Cash
{
public int cash_id { get; set; }
public string cash_name { get; set; }
public int cellar_id { get; set; }
public int cashstatus_id { get; set; }
}
public class Cellars
{
public string cellar_name { get; set; }
public int cellar_id { get; set; }
}
public class CashStatus
{
public int cashstatus_id { get; set; }
public string cashstatus_name { get; set; }
}
public class CashOpeningsAssignments
{
public int user_id { get; set; }
public int cash_id { get; set; }
public int cashopeningassignmentstatus_id { get; set; }
}
public class Users
{
public string user_firstname { get; set; }
public string user_lastname { get; set; }
public int user_id { get; set; }
}
See Also
https://msdn.microsoft.com/en-us/library/vstudio/bb355419%28v=vs.100%29.aspx