Add values to a list inside a list Linq - c#

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

Related

Filter data from 2 lists with diferent models C#

I have this models
public class RoutingAttributeModel
{
public int Bus_No { get; set; }
public int Attribute_No { get; set; }
public string Attribute_Name { get; set; }
public string Status { get; set; }
public string Notes { get; set; }
}
public class AgentRoutingAttributeModel
{
public int Agent_No { get; set; }
public int Bus_No { get; set; }
public int Attribute_No { get; set; }
public string Attribute_Name { get; set; }
public string Status { get; set; }
}
List<RoutingAttributeModel> lstComplete = new List<RoutingAttributeModel>();
List<AgentRoutingAttributeModel> lstAssigned = new List<AgentRoutingAttributeModel>();
Filled this with some data
Is it possible to filter with Linq? I want to save in a new list the diferent content between lstComplete and lstAssigned
I was trying to join both lists but got stuck there
var results1 = from cl in lstComplete
join al in lstAssigned
on cl.Attribute_No equals al.Attribute_No
select cl;
you can use linq
as my understanding, you try to find linked by attribute_No records and have a list of not matching properties?
lstComplete.Add(new RoutingAttributeModel(){
Attribute_Name = "aaa",
Attribute_No = 1,
Bus_No = 1,
Notes = "",
Status = "status"
});
lstAssigned.Add(new AgentRoutingAttributeModel()
{
Attribute_No = 1,
Agent_No = 10,
Bus_No = 1,
Attribute_Name = "bbb",
Status = "status2"
});
var lst = lstComplete
.Join(lstAssigned,
complete => complete.Attribute_No,
assigned => assigned.Attribute_No,
(complete, assigned) => new { lstComplete = complete, lstAssigned = assigned })
.Select(s => new { s.lstComplete, s.lstAssigned})
.Where(w=>
w.lstAssigned.Attribute_Name != w.lstComplete.Attribute_Name
|| w.lstAssigned.Bus_No != w.lstComplete.Bus_No
)
.ToList()
.Dump();
so result would be
You could try the following query
var filteredList = lstComplete
.Where(x => !lstAssigned.Any(y => y.Attribute_No == x.Attribute_No));

LINQ select List where sub-list all items contains another list

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();

How to join two LINQ queries

I have two related entities with composite keys:
public class Event
{
public string ID1 { get; set; }
public int ID2 { get; set; }
public DateTime EventDate { get; set; }
public string EventData { get; set; }
public string DocID1 { get; set; }
public int DocID2 { get; set; }
}
public class EventDocument
{
public string ID1 { get; set; }
public int ID2 { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Number { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
Is there a possibility to filter first both of them by some criteria and then to join results because of big amount of records?
Acctually I can reach related Events when I filter EventDocuments, but I also need a possibility to filter Event and EventDocument in one time.
I am trying to do like this:
var events = ModelContext.Events.AsNoTracking().Select(x => x);
events = events.Where(x => x.EventData.StartsWith(FilterCriteria));
var eventDocuments = ModelContext.EventDocuments.AsNoTracking().Select(x => x);
eventsDocuments = eventDocuments.Where(x => x.LastName.StartsWith(FilterLastName));
And now I need to join these to queries and get a result - filtered and joined data from two entities
Trying to do like this:
var result = eventDocuments.Join(events,
doc => new { doc.ID1, doc.ID2 },
ev => new { cross.DocID1, cross.DocID2},
(doc, ev) => new { EventDocument = doc, Event = ev });
You can simply query both sets with SelectMany. In query syntax this would look like:
var eventsQry =
from eventDocument in eventDocuments
where eventDocument.LastName.StartsWith(FilterLastName)
from ev in events
where ev.EventData.StartsWith(FilterCriteria) && (ev.ID1 == eventDocument.ID1) && (ev.ID2 == eventDocument.ID2)
select new { eventDocument, ev };
You don't need to use one query to filter your results. You can combine multiple queries:
var eventsQry =
from ev in events
where ev.EventData.StartsWith(FilterCriteria)
select ev
var documentsQry =
from eventDocument in documentsQry
where eventDocument.LastName.StartsWith(FilterLastName)
select eventDocument;
var combinedQry =
from eventDocument in documentsQry
from ev in eventsQry
where (ev.ID1 == eventDocument.ID1) && (ev.ID2 == eventDocument.ID2)
select new { eventDocument, ev };

Find Unique count on field using LINQ

I am trying to determine the Distinct count for a particular field in a collection of objects.
private static RemittanceCenterBatchSummaryListModel SummarizeFields(RemittanceCenterSummaryListModel remittanceCenterSummaryListModel)
{
var result = remittanceCenterSummaryListModel.RemittanceBatchSummaryRecord.GroupBy(x => new{x.FileId, x.SourceFileName, x.BatchCode, x.BatchType})
.Select(x => new RemittanceCenterBatchSummarizedModel()
{
FileId = x.Key.FileId,
SourceFileName = x.Key.SourceFileName,
BatchCode = x.Key.BatchCode,
BatchType = x.Key.BatchType,
DetailRecordCountAdc = x.Count(y => y.BillingSystemCode == BillingSystemCode.Adc),
DetailRecordCountNotAdc = x.Count(y => y.BillingSystemCode == BillingSystemCode.Exd),
AmountAdc = x.Where(y => y.BillingSystemCode == BillingSystemCode.Adc).Sum(y => y.PaymentAmount),
AmountNotAdc = x.Where(y => y.BillingSystemCode == BillingSystemCode.Exd).Sum(y => y.PaymentAmount),
UniqueFileCount = x.Select(y => x.Key.FileId).Distinct().Count()
});
return CreateSummaryListModel(result);
}
Input entities:
public class RemittanceCenterSummaryListModel
{
public RemittanceCenterSummaryListModel()
{
this.RemittanceBatchSummaryRecord = new List<RemittanceBatchProcessingModel>();
}
public List<RemittanceBatchProcessingModel> RemittanceBatchSummaryRecord { get; private set; }
}
public class RemittanceCenterBatchSummarizedModel
{
public string FileId { get; set; }
public string SourceFileName { get; set; }
public string BatchCode { get; set; }
public string BatchType { get; set; }
public int DetailRecordCountAdc { get; set; }
public int DetailRecordCountNotAdc { get; set; }
public int DetailRecordCountTotal { get; set; }
public decimal AmountAdc { get; set; }
public decimal AmountNotAdc { get; set; }
public decimal AmountTotal { get; set; }
public BillingSystemCode BillingSystemCode { get; set; }
public int UniqueFileCount { get; set; }
}
private static RemittanceCenterBatchSummaryListModel CreateSummaryListModel(IEnumerable<RemittanceCenterBatchSummarizedModel> summaryModels)
{
var summaryModelList = new RemittanceCenterBatchSummaryListModel();
foreach (var summaryRec in summaryModels)
{
var summaryModel = new RemittanceCenterBatchSummarizedModel
{
FileId = summaryRec.FileId,
SourceFileName = summaryRec.SourceFileName,
BatchCode = summaryRec.BatchCode,
BatchType = summaryRec.BatchType,
DetailRecordCountAdc = summaryRec.DetailRecordCountAdc,
DetailRecordCountNotAdc = summaryRec.DetailRecordCountNotAdc,
AmountAdc = summaryRec.AmountAdc,
AmountNotAdc = summaryRec.AmountNotAdc,
UniqueFileCount = summaryRec.UniqueFileCount
};
summaryModelList.RemittanceBatchSummary.Add(summaryModel);
}
return summaryModelList;
}
Example input records:
Record1:
FileId: '123'
SourceFileName: 'test.file.txt'
BatchCode: 'aaa'
BatchType: 'scanned'
PaymentAmount: '50.00'
BillingSystemCode: 'Adc'
Record1:
FileId: '1234'
SourceFileName: 'test.file2.txt'
BatchCode: 'aab'
BatchType: 'scanned'
PaymentAmount: '52.00'
BillingSystemCode: 'Adc'
ActualOuput for UniqueFileCount Field:
UniqueFileCount = 1
ExpectedOutput results for UniqueFileCount Field:
UniqueFileCount = 2
What am I doing wrong?
It sounds like you want the distinct count of FileId for the entire collection and not just for each group, which will always be 1 since FileId is one of the fields you group on. If that is the case then you can just calculate that count first
int distinctFileIds = remittanceCenterSummaryListModel.RemittanceBatchSummaryRecor‌​d
.Select(x => x.FileId)
.Distinct()
.Count();
Then use that in your Linq query
UniqueFileCount = distinctFileIds

Sort and allocate objects in a list

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; }
}

Categories