C# MongoDB Driver
public class Details
{
[BsonId]
public ObjectId Id { get; set; }
public string GroupID { get; set; }
public Names[] Name{ get; set; }
}
public class Names
{
public string FullName { get; set; }
public int Age { get; set; }
public int Status {get; set;}
}
Input
var req = [{FullName = "ABC",
Age = 15,
Status = 0}
{FullName = "XYZ",
Age = 16,
Status = 0},
{FullName = "QAZ",
Age = 14,
Status = 0}]
MongoDB Query
var updateDefinationValues = new List<UpdateDefinition<Details>>();
List<FilterDefinition<Details>> listDetailsFilter = new List<FilterDefinition<Details>>();
foreach (var il in req.Names)
{
FilterDefinition<Details> detailsFilter = Builders<Details>.Filter.Where(x => x.GroupID == requestId && x.Names.Any(i => i.FullName == il.FullName));
updateDefinationValues.Add(Builders<Details>.Update.Set(x => x.Names.ElementAt(-1).Status, 1));
listDetailsFilter.Add(detailsFilter);
}
FilterDefinition<Details> filter = Builders<Details>.Filter.Or(test);
var combinedUpdate = Builders<Details>.Update.Combine(updateDefinationValues);
var isUpdated = UpdateOne(_db, filter, combinedUpdate);
The above query is working when listDetailsFilter count == 1.
Error: The positional Operation did not find the match needed for this query
And it is not working when listDetailsFilter count > 1.
Related
Given the data below, I am trying to write a LINQ statement that will check if SubscriptionId is null by using (grp2.Select(y => y.SubscriptionId) == null). This must be failing because it will always go into the else section and return ,4 which is not what I am looking for. Is this the correct way to check if this value is null?
LINQPad Example
class Subscription
{
public int? SubscriptionId { get; set; }
public int ParentProductId { get; set; }
public string ParentProductName { get; set; }
public string ChildProductName { get; set; }
public int ChildProductId { get; set; }
public int GroupId { get; set; }
public DateTime? EndDate { get; set; }
}
class SubscriptionViewModel
{
public int SubscriptionId { get; set; }
public int ParentProductId { get; set; }
public string ParentProductName { get; set; }
public string SubscriptionIds { get; set; }
public int GroupId { get; set; }
}
class SubscriptionChildViewModel
{
public string ChildProductName { get; set; }
public int ChildProductId { get; set; }
}
void Main()
{
List<Subscription> ListOfSubscription = new List<Subscription>();
ListOfSubscription.Add(new Subscription() { SubscriptionId = null, ParentProductId = 4, ChildProductId = 4, ParentProductName = "Product 1", ChildProductName = "Product 1", GroupId = 362, });
ListOfSubscription.Add(new Subscription() { SubscriptionId = 2, ParentProductId = 114, ChildProductId = 1, ParentProductName = "Product 2", ChildProductName = "Product 3", GroupId = 1, });
ListOfSubscription.Add(new Subscription() { SubscriptionId = 3, ParentProductId = 114, ChildProductId = 2, ParentProductName = "Product 2", ChildProductName = "Product 4", GroupId = 1, });
var groupedSubscriptions = ListOfSubscription.GroupBy(u => u.GroupId);
var result = groupedSubscriptions.Select(grp1 => new
{
GroupId = grp1.Key,
Subscriptions = grp1.GroupBy(subscr => new
{
subscr.ParentProductId,
subscr.ParentProductName,
})
.Select(grp2 => new SubscriptionViewModel
{
GroupId = grp1.Key,
ParentProductId = grp2.Key.ParentProductId,
ParentProductName = grp2.Key.ParentProductName,
SubscriptionIds = (grp2.Select(y => y.SubscriptionId) == null) ? null : (string.Format("{0},{1}", string.Join(",", grp2.Select(y => y.SubscriptionId)), grp2.Key.ParentProductId))
})
});
var x = result.SelectMany((s => s.Subscriptions));
Console.Write(x);
}
Change your logic
(grp2.Select(y => y.SubscriptionId) == null)
to
grp2.Where(y => y.SubscriptionId == null).Count() > 0
Remove that bracket y.SubscriptionId)
This could work for you, to work with nulleables you can use "HasValue" instead of directly comparing with null.
SubscriptionIds = (grp2.Select( y => y.SubscriptionId.HasValue ) == null) ? null : (string.Format("{0},{1}", string.Join(",", grp2.Select(y => y.SubscriptionId.HasValue)), grp2.Key.ParentProductId))
Microsoft suggests using HasValue for nulleables types
This was kind of a hard question to ask but this is my problem:
I'm populating a grid with data I obtain from a different class, this class uses a (generic) Model that can represent multiple models:
Model(can represent Vessel or Container):
public class DataGridInstallationRow
{
[Key]
public string Name { get; set; }
//Vessel
public int IMO { get; set; }
public int MMSI { get; set; }
public int EEOI { get; set; }
public int FOC { get; set; }
[Display(Name = "Total Fuel Mass")]
public int TotalFuelMass { get; set; }
[Display(Name = "Average Speed")]
public int AverageSpeed { get; set; }
[Display(Name = "Total Distance Sailed")]
public int TotalDistanceSailed { get; set; }
//Container
[Display(Name = "Generated by Sun")]
public int EnergyGeneratedBySun { get; set; }
[Display(Name = "Generated by Wind")]
public int EnergyGeneratedByWind { get; set; }
[Display(Name = "Generated by Generator")]
public int EnergyGeneratedByGenerator { get; set; }
[Display(Name = "Consumed by EV's")]
public int EnergyConsumedByEV { get; set; }
[Display(Name = "Consumed by Construction Site")]
public int EnergyConsumedByConstructionSite { get; set; }
}
This model is used in my provider:
if (fleet.Type.Equals("Container"))
{
return Enumerable.Range(0, 10).Select(i => new DataGridInstallationRow()
{
Name = $"Container {i}",
EnergyGeneratedBySun = 13,
EnergyGeneratedByWind = 19,
EnergyGeneratedByGenerator = 3,
EnergyConsumedByEV = 15,
EnergyConsumedByConstructionSite = 24
}).ToList();
}
else
{
return Enumerable.Range(0, 10).Select(i => new DataGridInstallationRow()
{
Name = $"Vessel {i}",
IMO = 231,
MMSI = 1344,
EEOI = 8121,
FOC = 123,
TotalFuelMass = 6817,
AverageSpeed = 14,
TotalDistanceSailed = 1560
}).ToList();
}
As u can see, depending on the Fleet.Type, one of the other is filled in. If Fleet.Type is container the object will look like this:
As u can see the properties of "Vessel" is filled in aswell with all "0", I want these to be null instead of "0" because my datagrid is filled with both models now:
Whats best practice to avoid and fix this?
UPDATE
Applied solution of Dogac:
if (fleet.Type.Equals("Container"))
{
return Enumerable.Range(0, 10).Select(i => new DataGridInstallationRow()
{
Name = $"Container {i}",
EnergyGeneratedBySun = 13,
EnergyGeneratedByWind = 19,
EnergyGeneratedByGenerator = 3,
EnergyConsumedByEV = 15,
EnergyConsumedByConstructionSite = 24
}).Where(row =>
{
return row.EnergyGeneratedBySun.HasValue &&
row.EnergyGeneratedByWind.HasValue &&
row.EnergyGeneratedByGenerator.HasValue &&
row.EnergyConsumedByEV.HasValue &&
row.EnergyConsumedByConstructionSite.HasValue;
}).ToList();
}
else
{
return Enumerable.Range(0, 10).Select(i => new DataGridInstallationRow()
{
Name = $"Vessel {i}",
IMO = 231,
MMSI = 1344,
EEOI = 8121,
FOC = 123,
TotalFuelMass = 6817,
AverageSpeed = 14,
TotalDistanceSailed = 1560
}).Where(row =>
{
return row.IMO.HasValue &&
row.MMSI.HasValue &&
row.EEOI.HasValue &&
row.FOC.HasValue &&
row.TotalFuelMass.HasValue &&
row.AverageSpeed.HasValue &&
row.TotalDistanceSailed.HasValue;
}).ToList();
}
Is still not working, im again receiving a list with nullable items.
Thanks in advance
Try making all properties nullable.
Like this:
// Vessel
public int? IMO { get; set; }
public int? MMSI { get; set; }
public int? EEOI { get; set; }
public int? FOC { get; set; }
Edit regarding comment:
Enumerable.Range(0, 10).Select(i => new DataGridInstallationRow()
{
Name = $"Vessel {i}",
IMO = 231,
MMSI = 1344,
EEOI = 8121,
FOC = 123,
TotalFuelMass = 6817,
AverageSpeed = 14,
TotalDistanceSailed = 1560
}).Where(row =>
{
return row.IMO.HasValue &&
row.MMSI.HasValue &&
row.EEOI.HasValue &&
row.FOC.HasValue &&
row.TotalFuelMass.HasValue &&
row.AverageSpeed.HasValue &&
row.TotalDistanceSailed.HasValue;
}).ToList();
I have two database tables and I'm attempting to create a union query from them. They have different structures:
public partial class Notes
{
public int ID { get; set; }
public int VisitID { get; set; }
public string Note { get; set; }
public DateTime PostDate { get; set; }
public decimal AcctBalance {get; set; }
}
public partial class SystemNotes
{
public int ID {get; set;}
public int VisitID {get; set;}
public int FacilityID {get; set;}
public string Note {get; set;
public DateTime NoteDate {get ;set; }
}
What I want to do is end up with a list of all the data in Notes format sorted by PostDate. What I've tried so far is this:
List<Notes> requests = new List<Notes>();
requests = _context.Notes.Where(i => i.VisitID == VisitID && i.isActive == true).ToList();
List<SystemNotes> requests_s = new List<SystemNotes>();
requests_s = _context.SystemNotes.Where(i => i.VisitID == VisitID).ToList();
var unionA = from a in requests
select new
{
a.ID,
a.VisitID,
a.Note,
a.PostDate,
a.AcctBalance
};
var unionB = from b in requests_s
select new Notes()
{
ID = b.ID,
VisitID = (int)b.VisitID,
Note = b.Note,
PostDate = b.NoteDate,
AcctBalance = (decimal)0.00
};
List<Object> allS = (from x in unionA select (Object)x).ToList();
allS.AddRange((from x in unionB select (Object)x).ToList());
However, PostDate is no longer recognized as an element inside the Object so I can't sort on it. Also, it's in Object format not in Notes format which is what I want for where I'm sending my data. I'm stuck on this one point. Can you assist? Or am I doing this the wrong way in general?
If I correctly understand what you want:
List<Notes> myNotes = new List<Notes> {
new Notes () {
ID = 1,
VisitID = 2
}
};
List<SystemNotes> mySystemNotes = new List<SystemNotes> {
new SystemNotes () {
ID = 3,
VisitID = 4
}
};
var result = myNotes.Select (mn => new { mn.ID, mn.VisitID })
.Union(mySystemNotes.Select (msn => new { msn.ID, msn.VisitID }))
.OrderByDescending(a=>a.ID);
foreach (var currentItem in result)
{
Console.WriteLine ("ID={0}; VisitID={1}", currentItem.ID, currentItem.VisitID);
}
I have created 2 models to store the results of an sql query. Now I would like to join them for each of the week's... (week1 = Record_id, week2 = Record_id)
to get a new Object in which I would have all the data from the 1st model, as well as map data from the "Category" Model to it.
I created a new Model for it, but I am not sure how to write a linq query
First Model:
public class CustomData
{
public string full_name { get; set; }
public string location { get; set; }
public int week1 { get; set; }
public int week2 { get; set; }
public int week3 { get; set; }
}
Second Model:
public class Category
{
public int Record_ID { get; set; }
public int Color{ get; set; }
public string Name { get; set; }
}
New Model for end result:
public class WeekView
{
public string full_name { get; set; }
public string location { get; set; }
public Category week1 { get; set; }
public Category week2 { get; set; }
public Category week3 { get; set; }
}
This should work:
List<CustomData> list = new List<CustomData>();
list.Add(new CustomData() { full_name = "test", location = "test", week1 = 0, week2 = 1, week3 = 2 });
list.Add(new CustomData() { full_name = "test2", location = "test2", week1 = 0, week2 = 12, week3 = 22 });
List<Category> categories = new List<Category>();
categories.Add(new Category { Color = 0, Name = "testName", Record_ID = 0 });
categories.Add(new Category { Color = 1, Name = "testName1", Record_ID = 1 });
categories.Add(new Category { Color = 2, Name = "testName2", Record_ID = 2 });
categories.Add(new Category { Color = 3, Name = "testName3", Record_ID = 12 });
categories.Add(new Category { Color = 4, Name = "testName4", Record_ID = 22 });
List<WeekView> results = new List<WeekView>();
results.AddRange(list.Select(x=>
new WeekView() { full_name = x.full_name,
location = x.location,
week1 = categories.FirstOrDefault(c => c.Record_ID == x.week1),
week2 = categories.FirstOrDefault(c => c.Record_ID == x.week2),
week3 = categories.FirstOrDefault(c => c.Record_ID == x.week3)
}));
Try out the following:
var result = (from cd in CustomDatas
join ca1 in Categories on cd.week1 equals ca.Record_ID into ca1r
from ca1 in ca1r.DefaultIfEmpty()
join ca2 in Categories on cd.week2 equals ca.Record_ID into ca2r
from ca2 in ca2r.DefaultIfEmpty()
join ca3 in Categories on cd.week3 equals ca.Record_ID into ca3r
from ca3 in ca3r.DefaultIfEmpty()
select new {
full_name = cd.full_name,
location = cd.location,
week1 = ca1,
week2 = ca2,
week3 = ca3
}
I have a an object Quiz that looks like :
public class Quiz
{
public int Id { get; set; }
public ICollection<MathQuiz> MathQuizzes { get; set; }
}
MathQuizze object looks like :
public class MathQuiz
{
public int Id { get; set; }
public int QuizId{ get; set; }
public Quiz Quiz{ get; set; }
public int AnswerId { get; set; }
public Answer Answer { get; set; }
public int TagId{ get; set; }
public Tag Tag { get; set; }
public bool IsCorrect { get; set; }
}
And have an object(UserQuizzes) that looks like:
public class UserQuizes
{
public int Id { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public int QuizId { get; set; }
public Quiz Quiz { get; set; }
}
UserQuizzes is just class that express many to many relationship between users and quizzes.
This is a sample data :
List<Quiz> quizzes = new List<Quiz>();
quizzes.Add(new Quiz{ Id = 1, MathQuizzes = new List<MathQuiz>{
new MathQuiz { AnswerId = 58, TagId = 1, IsCorrect = false },
new MathQuiz { AnswerId = 26, TagId = 2, IsCorrect = true },
new MathQuiz { AnswerId = 57, TagId = 3, IsCorrect = true },
new Quiz{ Id = 2, MathQuizzes = new List<MathQuiz>{
new MathQuiz { AnswerId = 59, TagId = 1, IsCorrect = false },
new MathQuiz { AnswerId = 87, TagId = 2, IsCorrect = true },
new MathQuiz { AnswerId = 25, TagId = 3, IsCorrect = true }, });
List<UserQuizzes> userQuizzes = new List<UserQuizzes>();
userQuizzes.Add(new Quiz{ QuizId = 1, UserId = 1},
userQuizzes.Add(new Quiz{ QuizId = 2, UserId = 1});
Please don't spend too much time criticizing, I just wanted to use something that everyone is pretty familiar with.
What i want to achieve is that group by userquizzes by MathQuiz TagId and get data something like this:
TagId : 1, IsCorrect: true(0), false(2);
TagId : 2, IsCorrect: true(2), false(0);
TagId : 3, IsCorrect: true(2), false(0);
The code you posted has typos, but here is the basic idea:
var query =
from q in quizzes
from mq in q.MathQuizzes
join uq in userQuizzes on q.Id equals uq.QuizId
group mq by mq.TagId into g
select new
{
TagId = g.Key,
Correct = g.Sum(e => e.IsCorrect ? 1 : 0),
Incorrect = g.Sum(e => e.IsCorrect ? 0 : 1)
};
Basically you need to get the effective source set by joining the data sets, and the do the regular grouping/calculating aggregates.