GroupBy bool and Select values for new list - c#

I am trying to get into more complex Linq queries and right away catch a point I am feeling stuck. I have a following list in DB:
ID ELAPSED TIME APPISRUNNING
1 12 TRUE
2 54 TRUE
3 32 FALSE
Where ELAPSED TIME is TimeSpan and APPISRUNNING is a bool.
I would like to build a chart based on these values (https://github.com/beto-rodriguez/LiveCharts2). Chart build fine with this:
Title = "Analytics";
this.ActivityChartSeries = new ISeries[]
{
new PieSeries<double> { Values = new double[] { 2 }},
new PieSeries<double> { Values = new double[] { 2 }},
new PieSeries<double> { Values = new double[] { 2 }},
new PieSeries<double> { Values = new double[] { 2 }},
new PieSeries<double> { Values = new double[] { 2 }},
};
Now I somehow need to first GroupBy bool and then select a new List? I have tried following:
IEnumerable<DataRecord> dataRecords = await this.DataStore.GetItemsAsync();
this.ActivityChartSeries = dataRecords
.GroupBy(g => g.AppIsRunning)
.Select(m => new
{ // BELOW IS TOTALLY UNCLEAR FOR ME
Values = m.Select(r => r.EngineElapsed.Ticks),
Name = m.Select(r => r.Name),
})
.Select(x =>
new PieSeries<double>
{
Values = new List<double> { x.Values.FirstOrDefault() },
Name = x.Name.FirstOrDefault(),
});
Type of assigned variable:
public IEnumerable<ISeries> ActivityChartSeries
This part is totally unclear for me:
Values = m.Select(r => r.EngineElapsed.Ticks),
Name = m.Select(r => r.Name),
How after GroupBy I can create two types of data? Basically I need
"Application Running" and "Values"
"Application is not Running" and "Values"
EDIT:
Code provided by Somar Zein compiles fine:
var results = activityChartSeries
.GroupBy(a=> a.AppIsRunning)
.Select(item=> new PieSeries<double>{
Name = item.Key ? "Application is Running" : "Application is not Running",
Values = item.Select(x=> Convert.ToDouble(x.ElapsedTime.Ticks)).ToList()
});
However as a result I am getting something like this, why it is reloading in a loop?
Here is result:
enter image description here
EDIT2:
So I have created an example for testing purposes:
Class:
public class DataModel
{
public int Id { get; set; }
public TimeSpan ElapsedTime { get; set; }
public bool AppIsRunning { get; set; }
}
Code:
List<DataModel> records = new List<DataModel>();
records.Add(new DataModel { Id = 1, ElapsedTime = new TimeSpan(1, 20, 30), AppIsRunning = true });
records.Add(new DataModel { Id = 2, ElapsedTime = new TimeSpan(1, 20, 30), AppIsRunning = true });
records.Add(new DataModel { Id = 3, ElapsedTime = new TimeSpan(1, 20, 30), AppIsRunning = true });
records.Add(new DataModel { Id = 4, ElapsedTime = new TimeSpan(1, 20, 30), AppIsRunning = true });
records.Add(new DataModel { Id = 5, ElapsedTime = new TimeSpan(1, 20, 30), AppIsRunning = true });
this.ActivityChartSeries = records
.GroupBy(g => g.AppIsRunning)
.Select(item => new PieSeries<double>
{
Name = item.Key ? "Running" : "Not Running",
Values = new double[] { 2, 4 },
});
I get the same reloading effect, even thou originally provided Example from LiveCharts work fine.

you could try doing something like following:
var results = activityChartSeries
.GroupBy(a=> a.AppIsRunning)
.Select(item=> new PieSeries<double>{
Name = item.Key ? "Application is Running" : "Application is not Running",
Values = item.Select(x=> Convert.ToDouble(x.ElapsedTime.Ticks)).ToList()
});
hope that could be helpful!

Related

Finding Unique Objects between collections

I have a test where I have two lists created. One represents data that I have gone and collected from a source (of which I have no control over) and the other representing a known data already in my repository.
They look like this:
var newAccounts = new[]
{
new Account
{
Id = 1,
SA_ID = 1,
SA_Name = "Sa_Name1",
RelationshipType = "new",
LE_ID = 1,
LE_GroupID = 1,
SiteID = 1,
MinDate = DateTime.Now.AddDays(-1),
MaxDate = DateTime.Now.AddDays(1),
DaysOn = 1,
Child1 = new List<Child1>{ new Child1
{
SiteID = 1,
MaxDate = DateTime.Today.AddDays(7),
MinDate = DateTime.Today.AddDays(1),
}
},
Child2 = new List<Child2>
{
new Child2
{
SA_ID = 1,
LastUpdate = DateTime.Now.AddDays(-1),
CommentText = "Account added",
Status = AccountStatus.AccountAdded.ToString(),
}
}
},
new Account
{
Id = 2,
SA_ID = 2,
SA_Name = "Sa_Name2",
RelationshipType = "new",
LE_ID = 2,
LE_GroupID = 2,
SiteID = 2,
MinDate = DateTime.Now.AddDays(-2),
MaxDate = DateTime.Now.AddDays(2),
DaysOn = 2,
},
new Account
{
Id = 3,
SA_ID = 3,
SA_Name = "Sa_Name3",
RelationshipType = "new",
LE_ID = 3,
LE_GroupID = 3,
SiteID = 3,
MinDate = DateTime.Now.AddDays(-3),
MaxDate = DateTime.Now.AddDays(3),
DaysOn = 3,
}
};
var knownAccounts = new[]
{
new Account
{
Id = 1,
SA_ID = 1,
SA_Name = "Sa_Name1",
RelationshipType = "new",
LE_ID = 1,
LE_GroupID = 1,
SiteID = 1,
MinDate = DateTime.Now.AddDays(-1),
MaxDate = DateTime.Now.AddDays(1),
DaysOn = 1,
Child1 = new List<Child1>{ new Child1
{
SiteID = 1,
MaxDate = DateTime.Today.AddDays(7),
MinDate = DateTime.Today.AddDays(1),
}
},
Child2 = new List<Child2>
{
new Child2
{
SA_ID = 1,
LastUpdate = DateTime.Now.AddDays(-1),
CommentText = "Account added",
Status = AccountStatus.AccountAdded.ToString(),
}
}
}
};
In my unit tests I am wanting to strip out Account ID 1 from newAccounts so I'm only left with 2 entries in my collection. These are my attempts thus far:
public List<T> ReturnUniqueEntriesList<T>(List<T> newAccounts, List<T> knownAccounts)
{
var a = knownAccounts.Intersect(newAccounts).ToList();
var listA = newAccounts.Except(knownAccounts).ToList();
var listB = knownAccounts.Except(newAccounts).ToList();
var result = listB.Intersect(listA).ToList();
return result;
}
When I run this the final result is 0. a also returns 0 and listA & listB simply return their respective objects.
What is it that I'm doing wrong / missing here? Any help would be appreciated
Override Equals and GetHashcode for Account so that they don't rely on the default implementations (memory address of the object). This means the C# will be able to equate them properly when executing an Except.
For example:
public class Account{
public override bool Equals(object other){
return other is Account a && a.Id == this.Id; //nb; is returns false if other is a null, even if it is an Account
}
public override int GetHashCode(){
return Id.GetHashCode();
}
}
As it is, the following two accounts are very different:
var a = new Account { Id = 1 };
var b = new Account { Id = 1 };
..because they live at different memory addresses.
By overriding Equals so that it compares the Id of the other, regardless the other properties, you can then essentially realize the situation you seem to describe of "two account objects with the same ID are equivalent"
If other properties factor into the decision, add those too. Hashcode.Combine is a useful method to combine several hashcodes for the puzzle of getting multiple properties' hashcodes to produce a suitable new signle hashcode - https://learn.microsoft.com/en-us/dotnet/api/system.hashcode.combine?view=net-5.0

Complex linq join in EF6

There are two entities, for example, job and solution.
Each of them has a date field and a level field and a quantity field.
It is necessary to combine them so that they are grouped first by level, then by month, and at the same time, their quantity must be summed up.
I tried different options, but nothing comes out at all. The main problem is grouping by months and summing the numbers in the enclosed sheets.
That is, the output should be one sequence of summed numbers, grouped by level, and then by month.
For example:
var jobs = new List<Job>()
{
new Job { Level = 1, Date = new DateTime(2019, 1, 1), Quantity = 111 },
new Job { Level = 1, Date = new DateTime(2019, 1, 20), Quantity = 222 },
new Job { Level = 2, Date = new DateTime(2019, 2, 1), Quantity = 333 },
new Job { Level = 2, Date = new DateTime(2019, 2, 20), Quantity = 444 }
};
var solutions = new List<Solution>()
{
new Solution { Level = 1, Date = new DateTime(2019, 2, 1), Quantity = 555 },
new Solution { Level = 2, Date = new DateTime(2019, 2, 20), Quantity = 666 },
new Solution { Level = 1, Date = new DateTime(2019, 1, 1), Quantity = 777 },
new Solution { Level = 2, Date = new DateTime(2019, 1, 20), Quantity = 888 }
};
Output:
Level 1 -> 1 Jan 2019 -> 1110 (111 + 222 + 777)
Level 1 -> 1 Feb 2019 -> 555
Level 2 -> 1 Jan 2019 -> 888
Level 2 -> 1 Feb 2019 -> 1443 (333 + 444 + 666)
And so on. And yes, all this is in EF6.
Try following which uses Concat. I create a class for the merging. It can also be done anonymously.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication116
{
class Program
{
static void Main(string[] args)
{
var jobs = new List<Job>()
{
new Job { Level = 1, Date = new DateTime(2019, 1, 1), Quantity = 111 },
new Job { Level = 1, Date = new DateTime(2019, 1, 20), Quantity = 222 },
new Job { Level = 2, Date = new DateTime(2019, 2, 1), Quantity = 333 },
new Job { Level = 2, Date = new DateTime(2019, 2, 20), Quantity = 444 }
};
var solutions = new List<Solution>()
{
new Solution { Level = 1, Date = new DateTime(2019, 2, 1), Quantity = 555 },
new Solution { Level = 2, Date = new DateTime(2019, 2, 20), Quantity = 666 },
new Solution { Level = 1, Date = new DateTime(2019, 1, 1), Quantity = 777 },
new Solution { Level = 2, Date = new DateTime(2019, 1, 20), Quantity = 888 }
};
List<LevelDateQuantity> concat = jobs.Select(x => new LevelDateQuantity() { Date = x.Date, Level = x.Level, Quantity = x.Quantity})
.Concat( solutions.Select(x => new LevelDateQuantity() { Date = x.Date, Level = x.Level, Quantity = x.Quantity})).ToList();
List<LevelDateQuantity> results = concat.OrderBy(x => x.Level).ThenBy(x => x.Date)
.GroupBy(x => new { level = x.Level, date = new DateTime(x.Date.Year, x.Date.Month,1)})
.Select(x => new LevelDateQuantity() { Level = x.Key.level, Date = x.Key.date, Quantity = x.Sum(y => y.Quantity)})
.ToList();
}
}
public class LevelDateQuantity
{
public int Level { get; set; }
public DateTime Date { get; set; }
public int Quantity { get; set; }
}
public class Job : LevelDateQuantity
{
public int Level { get; set; }
public DateTime Date { get; set; }
public int Quantity { get; set; }
}
public class Solution : LevelDateQuantity
{
public int Level { get; set; }
public DateTime Date { get; set; }
public int Quantity { get; set; }
}
}
Oath, because we can not see your poco class structure we don't know if the two tables are seperate or has a one to many relation to a master table, so by the code you have provided I would do this ;
var jobs = new List<Job>()
{
new Job { Level = 1, Date = new DateTime(2019, 1, 1), Quantity = 111 },
new Job { Level = 1, Date = new DateTime(2019, 1, 20), Quantity = 222 },
new Job { Level = 2, Date = new DateTime(2019, 2, 1), Quantity = 333 },
new Job { Level = 2, Date = new DateTime(2019, 2, 20), Quantity = 444 }
};
var solutions = new List<Solution>()
{
new Solution { Level = 1, Date = new DateTime(2019, 2, 1), Quantity = 555 },
new Solution { Level = 2, Date = new DateTime(2019, 2, 20), Quantity = 666 },
new Solution { Level = 1, Date = new DateTime(2019, 1, 1), Quantity = 777 },
new Solution { Level = 2, Date = new DateTime(2019, 1, 20), Quantity = 888 }
};
foreach (var sol in solutions)
{
var jb = new Job();
jb.Level = sol.Level;
jb.Date = sol.Date ;
jb.Quantity= sol.Quantity;
jobs.Add(jb);
}
var result = Jobs.GroupBy(x=> new { x.Level, x.Date}).Select(x=> new
{
level = x.Key.Level,
date = x.Key.Date,
sumQ = x.Sum(y => y.Quantity )
});
I haven't tested the code and not wrote in in a compiler so there might be some typeerrors apart from that this should solve your problem.

Combine duplicates in a list

In my current test project I'm looking to combine all objects in a list where one of their values is the same as in another object, I would then like to check the other values under these objects and combine them together, here's and example:
Object1
{
id = 111,
price1 = 10,
price 2 = 20
}
Object2
{
id = 222,
price1 = 10,
price 2 = 20
}
Object3
{
id = 111,
price1 = 30,
price 2 = 70
}
Object4
{
id = 444,
price1 = 15,
price 2 = 25
}
From the above Object1 and and Object3 would be combined based on their related 'id' value, their prices would then be combined and would result in the following object replacing Object1 and Object3 in a list:
NewObject
{
id = 111,
price1 = 40,
price 2 = 90
}
The end list would then look like this:
NewObject
{
id = 111,
price1 = 40,
price 2 = 90
}
Object2
{
id = 222,
price1 = 10,
price 2 = 20
}
Object4
{
id = 444,
price1 = 15,
price 2 = 25
}
So far I would go about obtaining the value using linq as follows:
Select all with the same id add thier values
Create new object with combined values for all obtained in step 1 and add to new list
Continue over list and if the 'id 'already exists in new list then ignore it as it's already been combined into the new list
Is there maybe a quicker easier way with a single LINQ statement?
var result = source
.GroupBy(x => x.id,
(key, values) => new {
id = key,
price1 = values.Sum(x => x.price1),
price2 = values.Sum(x => x.price2)
});
try group by
var combined = list.GroupBy(x => x.id, x => x).Select(x => new ListObj()
{
id = x.Key,
price1 = x.Sum(s => s.price1),
price2 = x.Sum(s => s.price2),
});
whole console app:
class Program
{
static void Main(string[] args)
{
var list = new List<ListObj>()
{
new ListObj()
{
id = 111,
price1 = 10,
price2 = 20
},
new ListObj()
{
id = 222,
price1 = 10,
price2 = 20
},
new ListObj()
{
id = 111,
price1 = 30,
price2 = 70
},
new ListObj()
{
id = 444,
price1 = 15,
price2 = 25
},
};
var combined = list
.GroupBy(x => x.id, x => x)
.Select(x => new ListObj()
{
id = x.Key,
price1 = x.Sum(s => s.price1),
price2 = x.Sum(s => s.price2),
});
Console.ReadKey();
}
}
public class ListObj
{
public int id { get; set; }
public int price1 { get; set; }
public int price2 { get; set; }
}

Join three list using multiple columns c# linq lambda

I have these lists:
var subjects = new List<SubjectModel>
{
new SubjectModel { subjId = 1, subjName = "Math" },
new SubjectModel { subjId = 2, subjName = "Science" },
new SubjectModel { subjId = 3, subjName = "History" },
new SubjectModel { subjId = 4, subjName = "Language" }
};
var quizzes = new List<QuizModel>
{
new QuizModel { quizId = 1, quizDate = DateTime.Parse("2016-11-25"), quizScore = 10, subjectId = 1 },
new QuizModel { quizId = 2, quizDate = DateTime.Parse("2016-11-25"), quizScore = 15, subjectId = 1 },
new QuizModel { quizId = 3, quizDate = DateTime.Parse("2016-11-25"), quizScore = 8, subjectId = 2 },
new QuizModel { quizId = 4, quizDate = DateTime.Parse("2016-11-26"), quizScore = 13, subjectId = 1 },
new QuizModel { quizId = 5, quizDate = DateTime.Parse("2016-11-26"), quizScore = 20, subjectId = 2 }
};
var exams = new List<ExamModel>
{
new ExamModel { examId = 1, examDate = DateTime.Parse("2016-11-25"), examScore = 90, subjectId = 1 },
new ExamModel { examId = 2, examDate = DateTime.Parse("2016-11-25"), examScore = 88, subjectId = 2 },
new ExamModel { examId = 3, examDate = DateTime.Parse("2016-11-25"), examScore = 92, subjectId = 4 },
new ExamModel { examId = , examDate = DateTime.Parse("2016-11-26"), examScore = 84, subjectId = 1 },
};
var exercises = new List<ExerciseModel>
{
new ExerciseModel { exerciseId = 1, exerciseDate = DateTime.Parse("2016-11-25"), exerciseScore = 17, subjectId = 1 },
new ExerciseModel { exerciseId = 2, exerciseDate = DateTime.Parse("2016-11-25"), exerciseScore = 15, subjectId = 2 },
new ExerciseModel { exerciseId = 3, exerciseDate = DateTime.Parse("2016-11-26"), exerciseScore = 15, subjectId = 1 },
new ExerciseModel { exerciseId = 4, exerciseDate = DateTime.Parse("2016-11-26"), exerciseScore = 12, subjectId = 4 },
new ExerciseModel { exerciseId = 5, exerciseDate = DateTime.Parse("2016-11-26"), exerciseScore = 10, subjectId = 1 },
};
I was able to successfully group each of them by date and by subject.
var allQuizzes = quizzes.GroupBy(qz => qz.quizDate, (q, values) =>
new
{
Date = q,
Quizzes = values.GroupBy(v => v.subjectId, (c, values2) =>
new {
SubjectId = c,
QuizSum = values2.Sum(v2 => v2.quizScore)
})
});
var allExercises = exercises.GroupBy(ex => ex.exerciseDate, (e, values) =>
new {
Date = e,
Exercises = values.GroupBy(x => x.subjectId, (z, values2) =>
new {
SubjectId = z,
ExerSum = values2.Sum(r => r.exerciseScore)
})
});
var allExams = exams.GroupBy(ex => ex.examDate, (e, values) =>
new
{
Date = e,
Exercises = values.GroupBy(x => x.subjectId, (z, values2) =>
new
{
SubjectId = z,
ExamSum = values2.Sum(r => r.examScore)
})
});
However, I need to join all three of them to get the sum of all scores. The final table should display like this.
-----------------------------------------------------------------
| Date | Math | Science | History | Language |
| 11/25/2016 | 132 | 111 | 0 | 92 |
| 11/26/2016 | 122 | 20 | 0 | 12 |
-----------------------------------------------------------------
I tried to join them, but it can't seem to join by multiple columns.
I select from all 3 collections results in form of the same anonymous class (the same Idea had Andrei in first answer), that allows me just to collect all results together in all list, without mapping and converting.
var allQuiz = quizzes.GroupBy(x => new { x.subjectId, x.quizDate })
.Select(x => new {
Date = x.Key.quizDate,
Subj = x.Key.subjectId,
Sum = x.Sum(r=>r.quizScore)});
var allExam= exams.GroupBy(x => new { x.subjectId, x.examDate })
.Select(x => new {
Date = x.Key.examDate,
Subj = x.Key.subjectId,
Sum = x.Sum(r=>r.examScore)});
var allExc = exercises.GroupBy(x => new { x.subjectId, x.exerciseDate })
.Select(x => new {
Date = x.Key.exerciseDate,
Subj = x.Key.subjectId,
Sum = x.Sum(r=>r.exerciseScore)});
Combining of all results together:
var all = allQuiz.ToList();
all.AddRange(allExam.ToList());
all.AddRange(allExc.ToList());
var result = all.GroupBy(x => new { x.Date, x.Subj })
.Select(x => new { x.Key.Date, x.Key.Subj, Sum = x.Sum(s => s.Sum)});
var list = result.GroupBy(r => r.Date).Select(x => new {
Date = x.Key,
Math = x.SingleOrDefault(t=>t.Subj==1)?.Sum ?? 0,
Science = x.SingleOrDefault(t=>t.Subj==2)?.Sum ?? 0,
History = x.SingleOrDefault(t=>t.Subj==3)?.Sum ?? 0,
Language = x.SingleOrDefault(t=>t.Subj==4)?.Sum ?? 0,
});
Output in LinqPad:
Here is an idea. Instead of keeping the distinction while grouping, you could convert all three to the same structure. For instance:
var allQuizzes = quizzes.GroupBy(qz => qz.quizDate, (q, values) =>
new
{
Date = q,
Results = values.GroupBy(v => v.subjectId, (c, values2) =>
new {
SubjectId = c,
Sum = values2.Sum(v2 => v2.quizScore)
})
});
Notice names "Results" and "Sum" - you can use the same for the other two objects. And now you have three collections, all of the same structure:
{
Date:
Results: [
{SubjectId, Sum}
{SubjectId, Sum}
...
]
}
Since they are all the same now, you can stop treating them differently, use UNION to merge all three, group them by date and within that by subject. Then you could probably iterate through subject list to get necessary info, depends on what you mean by "final table".
This is what i came up with.
It may not be best optimized, but might be enough for you.
I rendered the results into a StringBuilder in my test.
var result =
quizzes.Select(q => new {SubjectId = q.subjectId, Date = q.quizDate, Score = q.quizScore})
.Union(exams.Select(e => new {SubjectId = e.subjectId, Date = e.examDate, Score = e.examScore}))
.Union(exercises.Select(e => new {SubjectId = e.subjectId, Date = e.exerciseDate, Score = e.exerciseScore}))
.GroupBy(arg => arg.Date,
(key, values)=>
new
{
Key = key,
Scores = values.GroupBy(v => v.SubjectId, (s, values2) => new { SubjectId = s, SumScore = values2.Sum(v2 => v2.Score) })
});
StringBuilder sb = new StringBuilder("Date\t\t");
foreach (SubjectModel subject in subjects)
{
sb.Append($"{subject.subjName}\t");
}
sb.AppendLine();
foreach (var record in result)
{
sb.Append($"{record.Key.ToShortDateString()}\t");
foreach (SubjectModel subject in subjects)
{
int sum = record.Scores.Where(s => s.SubjectId == subject.subjId).Select(s => s.SumScore).DefaultIfEmpty(0).Single();
sb.Append($"{sum}\t");
}
sb.AppendLine();
}
string finalTable = sb.ToString();
Instead of using three different anonymous objects to hold the results, make your own class:
public enum TestType
{
Quiz,
Exam,
Exercise,
}
public class TestScore
{
public TestType Type { get; set; }
public DateTime Date { get; set; }
public int Score { get; set; }
public int SubjectId { get; set; }
// Constructors - make a TestScore object
public TestScore(QuizModel q)
{
Type = TestType.Quiz;
Date = q.quizDate;
Score = q.quizScore;
SubjectId = q.SubjectId;
}
public TestScore(ExamModel e)
{
Type = TestType.Exam;
Date = e.examDate;
Score = e.examScore;
SubjectId = e.SubjectId;
}
public TestScore(ExerciseModel e)
{
Type = TestType.Exercise;
Date = e.exerciseDate;
Score = e.exerciseScore;
SubjectId = e.SubjectId;
}
}
Convert to TestScore:
List<TestScore> scores = new List<TestScore>();
scores.AddRange(quizzes.Select(q => new TestScore(q));
scores.AddRange(exams.Select(e => new TestScore(e));
scores.AddRange(exercises.Select(e => new TestScore(e));
Now you have one datasource instead of three, displaying the results becomes easy.

Get dates that contain all selected products

I have a calendar app where you select various combinations of products- a service goes out and gets the available dates based on the calendar date range. A date is only "Available" if ALL selected products are available on a particular date.
class SelectedProduct
{
public int ID { get; set; }
public int Qty { get; set; }
}
class AvailableInventory
{
public int ID { get; set; }
public DateTime Date { get; set; }
}
// List of selected products from user
List<SelectedProduct> SelectedProducts;
// populated from service with all dates for all products
List<AvailableInventory> AvailableInventory;
I want to be able to say get list of Available Inventory for each date that contains inventory for all ID's in selected products.
This is (non-working) pusdo code of a possible solution, I just don't know linq well enough to get it right
var results = List<AvailableInventory>();
foreach (var group in AvailableInventory.GroupBy(x => x.Date))
{
if (group.Contains(ALL ID's in SelectedProducts)
{
results.AddRange(group);
}
}
This groups inventory by date (ignoring the date portion), then selects only those groups that contain all selected product IDs, and finally selects all available inventory for the matching groups.
var results =
AvailableInventory.GroupBy(i => i.Date.Date)
.Where(g => !SelectedProducts.Select(p => p.ID)
.Except(g.Select(i => i.ID))
.Any())
.SelectMany(g => g);
The result is a collection of AvailableInventory.
You can group by the date, then filter out groups that don't have all the SelectedProducts.
// List of selected products from user
List<SelectedProduct> SelectedProducts = new List<SelectedProduct> {
new SelectedProduct { ID = 1, Qty = 1 },
new SelectedProduct { ID = 2, Qty = 2 },
};
// populated from service with all dates for all products
List<AvailableInventory> AvailableInventory = new List<AvailableInventory> {
new AvailableInventory { ID = 1, Date = new DateTime(2014, 04, 11) },
new AvailableInventory { ID = 2, Date = new DateTime(2014, 04, 11) },
new AvailableInventory { ID = 1, Date = new DateTime(2014, 04, 12) },
new AvailableInventory { ID = 2, Date = new DateTime(2014, 04, 13) },
new AvailableInventory { ID = 1, Date = new DateTime(2014, 04, 14) },
new AvailableInventory { ID = 2, Date = new DateTime(2014, 04, 14) },
};
var query = AvailableInventory.GroupBy(i => i.Date)
.Where(g => SelectedProducts.All(s => g.Any(i => i.ID == s.ID)));
foreach(var group in query)
{
Console.WriteLine("Date: {0}", group.Key);
foreach(var inventory in group)
{
Console.WriteLine(" Available: {0}", inventory.ID);
}
}
This would output:
Date: 4/11/2014 12:00:00 AM
Available: 1
Available: 2
Date: 4/14/2014 12:00:00 AM
Available: 1
Available: 2
I think this is what you are looking for. Try this
var result = AvailableInventory.Where(i => SelectedProducts.Any(x => x.ID == i.ID)).GroupBy(o => o.Date)
.Select(g => g.First()).ToList();
This is the test data I used based on your class definition for AvailableInventory and SelectedProduct
// List of selected products from user
List<SelectedProduct> SelectedProducts = new List<SelectedProduct> {
new SelectedProduct { ID = 1, Qty = 2 },
new SelectedProduct { ID = 2, Qty = 4 },
new SelectedProduct { ID = 5, Qty = 10 }
};
// populated from service with all dates for all products
List<AvailableInventory> AvailableInventory = new List<AvailableInventory> {
new AvailableInventory { ID = 1, Date = new DateTime(2014, 04, 01) },
new AvailableInventory { ID = 2, Date = new DateTime(2014, 04, 02) },
new AvailableInventory { ID = 3, Date = new DateTime(2014, 04, 02) },
new AvailableInventory { ID = 4, Date = new DateTime(2014, 04, 10) },
new AvailableInventory { ID = 5, Date = new DateTime(2014, 04, 10) }
};
This should give you only the records with ID = 1, ID = 2 and ID = 5 because that's what common between both AvailableInventory and SelectedProducts lists.
It would help if you actually tried something.
Given this:
List<SelectedProduct> SelectedProducts ;
List<AvailableInventory> AvailableInventory ;
Something like this will probably get what you want:
int[] DatesWithAllSelectedProductsAvailable =
AvailableInventory
.GroupBy( x => x.Date )
.Where ( g => g.All( x => SelectedProducts.Any( p => p.ID == x.ID ) ) )
.Select( x => x.Key )
.Distinct()
.OrderBy( x => x )
.ToArray()
;

Categories

Resources