C# Lambda Expressions Using Complex Objects - c#

How can I use a Lambda Expression on a List of Payment objects that have a List PaymentFields object. Here's what I currently have.
var list = paymentList.Where(payment => payment.PaymentFields.Any(field => field.FieldName == "ItemA" && field.FieldValue == "50");
That gives me payments that have ItemA as the Field Name and 50 as the Field Value. However, I want to COMPARE the two PaymentFields like so...
Where FieldName == "ItemA" && FieldValue = "50" && FieldName ItemA < FieldName ItemB
How would I do this?
I have two Objects:
public class Payment
{
public int Id { set; get; }
public string Name { set; get; }
public List<PaymentFields> PaymentFields { set; get; }
}
public class PaymentFields
{
public string FieldName { set; get; }
public string FieldValue { set; get; }
}
Here is an example Object:
var payment = new Payment()
{
Id = 1,
Name = "Test",
PaymentFields = new List<PaymentFields>()
{
new PaymentFields()
{
FieldName = "ItemA",
FieldValue = "20"
},
new PaymentFields()
{
FieldName = "ItemB",
FieldValue = "50"
}
}
};
Thanks for your help!

If you are absolutely sure there will be an "ItemA" and "ItemB", then this will work.
If either "ItemA" or "ItemB" is missing, it will throw an exception.
var list = paymentList
.Where(payment => payment.PaymentFields.Any(field => field.FieldName == "ItemA" && field.FieldValue == "50")
.Where(payment => payment.PaymentFields.First(field => field.FieldName == "ItemA").FieldValue
<
payment.PaymentFields.First(field => field.FieldName == "ItemB").FieldValue)
);

Related

Compare list against other list and modify

Supposed that I have these classes
public class Subject
{
public int Id { get; set; }
public string Category { get; set; }
public string Type { get; set; }
}
public class Student
{
public int Id { get; set; }
public List<MySubject> MySubjects { get; set; }
}
public class MySubject
{
public int Id { get; set; }
public string Category { get; set; }
public string Type { get; set; }
public string Schedule { get; set; }
public string RoomNumber { get; set; }
}
sample data
var subjects = new List<Subject>()
{
new Subject(){ Id = 1, Category = "Mathematics", Type = "Algebra" },
new Subject(){ Id = 2, Category = "Computer Science", Type = "Pascal" }
};
var student = new Student()
{ Id = 1, MySubjects = new List<MySubject>() {
new MySubject() {Id = 1, Category = "Mathematics", Type = "Algebra" },
new MySubject() {Id = 3, Category = "Mathematics", Type = "Trigonometry"},
}
};
//TODO: Update list here
student.MySubjects.ForEach(i => Console.WriteLine("{0}-{1}-{2}\t", i.Id, i.Category, i.Type));
the above line of code returns
1-Mathematics-Algebra
3-Mathematics-Trigonometry
which is incorrect. I need to return this
1-Mathematics-Algebra
2-Computer Science-Pascal
Basically I would like to modify and iterate the student.MySubjects and check its contents against subjects.
I would like to remove the subjects (3-Mathematics-Trigonometry) that are not present in the subjects and also ADD subjects that are missing (2-Computer Science-Pascal).
Can you suggest an efficient way to do this by searching/comparing using Category + Type?
Try like below.
// Remove those subjects which are not present in subjects list
student.MySubjects.RemoveAll(x => !subjects.Any(y => y.Category == x.Category && y.Type == x.Type));
// Retrieve list of subjects which are not added in students.MySubjects
var mySubjectsToAdd = subjects.Where(x => !student.MySubjects.Any(y => y.Category == x.Category && y.Type == x.Type))
.Select(x => new MySubject() {
Id = x.Id,
Category = x.Category,
Type = x.Type
}).ToList();
// If mySubjectsToAdd has any value then add it into student.MySubjects
if (mySubjectsToAdd.Any())
{
student.MySubjects.AddRange(mySubjectsToAdd);
}
student.MySubjects.ForEach(i => Console.WriteLine("{0}-{1}-{2}\t", i.Id, i.Category, i.Type));
// make an inner join based on mutual values to filter out wrong subjects.
var filteredList =
from mySubject in student.MySubjects
join subject in subjects
on new { mySubject.Category, mySubject.Type }
equals new { subject.Category, subject.Type }
select new MySubject { Id = mySubject.Id, Category = mySubject.Category, Type = mySubject.Type };
// make a left outer join to find absent subjects.
var absentList =
from subject in subjects
join mySubject in filteredList
on new { subject.Category, subject.Type }
equals new { mySubject.Category, mySubject.Type } into sm
from s in sm.DefaultIfEmpty()
where s == null
select new MySubject { Id = subject.Id, Category = subject.Category, Type = subject.Type };
student.MySubjects = filteredList.ToList();
student.MySubjects.AddRange(absentList.ToList());

Compare two Complex Objects in c#

I am trying to compare two objects and want to identify the difference in objects.
It works fine if I don't use List. But when I use List, Although the List in both objects are equal, it says it's not equal and go to check for List difference. Since, for now, I don't have the condition for list comparison it crashes and gives me this exception System.Reflection.TargetParameterCountException: 'Parameter count mismatch.'
I have taken help from one of the stackoverflow post from here. Here is my code which I have written so far.
public class Program
{
public static void Main()
{
Employee emp1 = OldEmployee();
Employee emp2 = NewEmployee();
var list = GetDifferingProperties(emp1, emp2);
foreach (var s in list)
Console.WriteLine(s);
}
public static IList<string> GetDifferingProperties(object source, object target)
{
var sourceType = source.GetType();
var sourceProperties = sourceType.GetProperties();
var targetType = target.GetType();
var targetProperties = targetType.GetProperties();
var result = new List<string>();
foreach (var property in
(from s in sourceProperties
from t in targetProperties
where s.Name == t.Name &&
s.PropertyType == t.PropertyType &&
!Equals(s.GetValue(source, null), t.GetValue(target, null))
select new { Source = s, Target = t }))
{
// it's up to you to decide how primitive is primitive enough
if (IsPrimitive(property.Source.PropertyType))
{
result.Add(property.Source.Name);
}
else
{
foreach (var subProperty in GetDifferingProperties(
property.Source.GetValue(source, null),
property.Target.GetValue(target, null)))
{
result.Add(property.Source.Name);
}
}
}
return result;
}
private static bool IsPrimitive(Type type)
{
return type == typeof(string)
|| type == typeof(int) || type == typeof(int?)
|| type == typeof(double) || type == typeof(double?)
|| type == typeof(bool) || type == typeof(bool?)
|| type == typeof(Guid) || type == typeof(Guid?)
|| type == typeof(DateTime) || type == typeof(DateTime?);
}
public static string GetPropertyDisplayName(PropertyInfo pi)
{
var dp = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().SingleOrDefault();
return dp != null ? dp.DisplayName : pi.Name;
}
private static Employee NewEmployee()
{
var contactDetail = new ContactDetails();
contactDetail.ContactNumber = "123456789";
var employeeAddress = new Address();
employeeAddress.AddressLine1 = "Microsoft Corporation";
employeeAddress.AddressLine2 = "One Microsoft Way";
employeeAddress.City = "Redmond";
employeeAddress.State = "WA";
employeeAddress.Zip = "98052-6399";
employeeAddress.ContactDetails = new List<ContactDetails>() { contactDetail };
var employee = new Employee();
employee.FirstName = "Bill";
employee.LastName = "Gates";
employee.MiddleName = "Middle Name";
employee.IsActive = true;
employee.JoinDate = new DateTime(2015, 10, 15);
employee.ReleaseDate = new DateTime(2015, 10, 15);
employee.EmployeeAddress = employeeAddress;
return employee;
}
private static Employee OldEmployee()
{
var contactDetail = new ContactDetails();
contactDetail.ContactNumber = "123456789";
var employeeAddress = new Address();
employeeAddress.AddressLine1 = "Microsoft Corporation";
employeeAddress.AddressLine2 = "One Microsoft Way";
employeeAddress.City = "Redmond";
employeeAddress.State = "WA";
employeeAddress.Zip = "98052-6399";
employeeAddress.ContactDetails = new List<ContactDetails>() { contactDetail };
var employee = new Employee();
employee.FirstName = "Bill";
employee.LastName = "Gates";
employee.MiddleName = "Middle Name";
employee.IsActive = true;
employee.JoinDate = new DateTime(2015, 10, 15);
employee.ReleaseDate = new DateTime(2015, 10, 15);
employee.EmployeeAddress = employeeAddress;
return employee;
}
}
public class ContactDetails
{
public string ContactNumber { get; set; }
}
public class Address
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public bool IsActive { get; set; }
public List<ContactDetails> ContactDetails { get; set; }
}
public class Employee
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public bool IsActive { get; set; }
public DateTime JoinDate { get; set; }
public DateTime? ReleaseDate { get; set; }
public Address EmployeeAddress { get; set; }
}
If I comment out the line employeeAddress.ContactDetails = new List<ContactDetails>() { contactDetail }; from oldEmployee and newEmployee, it works fine, and if there is any difference in EmployeeAddress it identifies it, and if there isn't any difference it doesn't. But if I uncomment this line employeeAddress.ContactDetails = new List<ContactDetails>() { contactDetail }; it takes out EmployeeAddress as it has difference, although it doesn't. Can some one please suggest what I am missing, I have spent a lot of time to identify the issue.
My Target to Achieve is, to make a list of properties that has a difference in Employee Object, for Example,
If FirstName in Employee has difference result list should
contain only FirstName
If FirstName in Employee and AddressLine1 in EmployeeAddress has difference result list should contain (FirstName, EmployeeAddress)
Similarly, If FirstName in Employee and ContactNumber in ContactDetails which is a List in Address has difference result list should contain (FirstName, EmployeeAddress), In this case result list still contains EmployeeAddress because ContactNumber is in EmployeeAddress which is in Employee, So our main focus is to get parent Properties that has difference is source and target object.
Point 1 and Point 2 are working as Expected. Iff I comment out employeeAddress.ContactDetails = new List<ContactDetails>() { contactDetail }; because it causing exception and also it coming with change although it doesn't have any change in source and target.
Any help would be highly appreciated, or you can suggest me some other way of implementation too.

C# ElasticSearch get external objects by nested list element property comparison

Let's suppose we have the following 2 objects (Please ignore the strange situation, as it is used only to model the real issue):
public class Person
{
public string FullName { get; set; }
public decimal TotalSalary { get; set; }
public List<Position> Positions { get; set; } = new List<Position>();
}
public class Position
{
public string Name { get; set; }
public bool IsCurrentPosition { get; set; }
public DateTime ExpirationDate { get; set; }
public int? MonthsWorked { get; set; }
public bool HasAverageLimitStatistic { get; set; } = false;
public int AverageMonthLimit { get; set; } = 0;
public decimal Salary { get; set; }
public string CompanyName { get; set; }
}
How do I write a query in NEST (C#) to find all people who work (or worked) on positions which are coming close to AverageMonthLimit in a timespan of a year, (positions without AverageMonthLimit are ignored); in case MonthsWorked is provided than compare it to AverageMonthLimit, otherwise take today's date and compare it to ExpirationDate.
PS: If the position has the statistic, then minimal AverageMonthLimit is of 36 months. People might work on several jobs.
NOTE: MSSQL script would probably look like:
SELECT *
FROM Person p
JOIN Position pos
ON pos.PersonId = p.Id
WHERE
pos.HasAverageLimitStatistic = 1
AND pos.AverageMonthLimit > pos.MonthsWorked
AND pos.AverageMonthLimit - 12 < pos.MonthsWorked
OR pos.HasAverageLimitStatistic = 0
AND DATEDIFF(MONTH, GETDATE(), pos.ExpirationDate) > 0
AND DATEDIFF(MONTH, GETDATE(), pos.ExpirationDate) < 12
UPDATE
Correct me if I'm wrong, but I presume the question boils down to the following, where query is unknown:
var response = _elasticClient.Search<Person>(s => s.Query(q =>
.DateRange(x => x
.Field(p => p.Employees
.First(pos => pos.HasAverageLimitStatistic == null)
.ExpirationDate)
    .GreaterThan(DateTime.Now)
.LessThan(DateTime.Now.AddYear(1))) 
// upper code finds customers who don't have statistic
|| q.Nested(x => x
.Path(p => p.Positions)
.Query(qq => qq.Script.Inline(" ?????? "))));
When querying against nested types, you need to use nested queries, which will take care of querying against the internal documents that nested types are modelled with.
Here's what your SQL query would look like in Elasticsearch
var searchResponse = client.Search<Person>(s => s
.Query(q => q
.Nested(n => n
.Path(p => p.Positions)
.Query(nq => (+nq
.Term(f => f.Positions.First().HasAverageLimitStatistic, true) && +nq
.Script(sq => sq
.Inline("doc['positions.monthsWorked'].value != 0 && doc['positions.averageMonthLimit'].value > doc['positions.monthsWorked'].value")
) && +nq
.Script(sq => sq
.Inline("doc['positions.monthsWorked'].value != 0 && (doc['positions.averageMonthLimit'].value - 12) < doc['positions.monthsWorked'].value")
)) || (+nq
.Term(f => f.Positions.First().HasAverageLimitStatistic, false) && +nq
.DateRange(d => d
.Field(f => f.Positions.First().ExpirationDate)
.GreaterThan(DateTime.Now.Date)
.LessThan(DateTime.Now.Date.AddYears(1))
))
)
)
)
);
There's a fair bit going here, so I'll break it down
Inside the top level query, a nested query will be performed. Since all predicates (i.e. WHERE clauses) are based on properties of nested types, these queries will all be inside of the nested query.
Specify the Path to the nested type on the top level type
Inside the nested query's query, 3 queries are &&ed together within parentheses for the first set of predicates where HasAverageLimitStatistic is true and 3 queries are &&ed together in parentheses for the second set of predicates where HasAverageLimitStatistic is false.
Since all queries test whether some condition is true or not, we can forgo calculating a score for them by making them filter clauses in a bool query. NEST has handy shorthand for bool query filter clauses in the form of the unary + operator. Similarly, there are overloaded operators combining queries with && and ||
Because you want to compare two properties on an indexed document, you need to use a script query to do this. In Elasticsearch 5.x, the default language for this is Painless.
The query DSL JSON for the above query is
{
"query": {
"nested": {
"query": {
"bool": {
"should": [
{
"bool": {
"filter": [
{
"term": {
"positions.hasAverageLimitStatistic": {
"value": true
}
}
},
{
"script": {
"script": {
"inline": "doc['positions.monthsWorked'].value != 0 && doc['positions.averageMonthLimit'].value > doc['positions.monthsWorked'].value"
}
}
},
{
"script": {
"script": {
"inline": "doc['positions.monthsWorked'].value != 0 && (doc['positions.averageMonthLimit'].value - 12) < doc['positions.monthsWorked'].value"
}
}
}
]
}
},
{
"bool": {
"filter": [
{
"term": {
"positions.hasAverageLimitStatistic": {
"value": false
}
}
},
{
"range": {
"positions.expirationDate": {
"gt": "2017-06-03T00:00:00-07:00",
"lt": "2018-06-03T00:00:00-07:00"
}
}
}
]
}
}
]
}
},
"path": "positions"
}
}
}
Finally, here's a complete example to demonstrate
void Main()
{
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var connectionSettings = new ConnectionSettings(pool)
.InferMappingFor<Person>(m => m
.IndexName("people")
)
.PrettyJson()
.DisableDirectStreaming()
.OnRequestCompleted(response =>
{
// log out the request
if (response.RequestBodyInBytes != null)
{
Console.WriteLine(
$"{response.HttpMethod} {response.Uri} \n" +
$"{Encoding.UTF8.GetString(response.RequestBodyInBytes)}");
}
else
{
Console.WriteLine($"{response.HttpMethod} {response.Uri}");
}
Console.WriteLine();
// log out the response
if (response.ResponseBodyInBytes != null)
{
Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
$"{Encoding.UTF8.GetString(response.ResponseBodyInBytes)}\n" +
$"{new string('-', 30)}\n");
}
else
{
Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
$"{new string('-', 30)}\n");
}
});
var client = new ElasticClient(connectionSettings);
if (client.IndexExists("people").Exists)
{
client.DeleteIndex("people");
}
client.CreateIndex("people", c => c
.Mappings(m => m
.Map<Person>(mm => mm
.AutoMap()
.Properties(p => p
.Nested<Position>(n => n
.Name(nn => nn.Positions)
.AutoMap()
)
)
)
)
);
client.IndexMany(new[] {
new Person
{
FullName = "Person 1",
TotalSalary = 100000,
Positions = new List<Position>
{
new Position
{
Name = "Janitor",
AverageMonthLimit = 5,
MonthsWorked = 3,
HasAverageLimitStatistic = true
}
}
},
new Person
{
FullName = "Person 2",
TotalSalary = 150000,
Positions = new List<Position>
{
new Position
{
Name = "Coach",
AverageMonthLimit = 5,
HasAverageLimitStatistic = true
}
}
},
new Person
{
FullName = "Person 3",
TotalSalary = 200000,
Positions = new List<Position>
{
new Position
{
Name = "Teacher",
HasAverageLimitStatistic = false,
ExpirationDate = DateTime.Now.AddMonths(6)
}
}
},
new Person
{
FullName = "Person 4",
TotalSalary = 250000,
Positions = new List<Position>
{
new Position
{
Name = "Head",
HasAverageLimitStatistic = false,
ExpirationDate = DateTime.Now.AddYears(2)
}
}
}
});
client.Refresh(IndexName.From<Person>());
var searchResponse = client.Search<Person>(s => s
.Query(q => q
.Nested(n => n
.Path(p => p.Positions)
.Query(nq => (+nq
.Term(f => f.Positions.First().HasAverageLimitStatistic, true) && +nq
.Script(sq => sq
.Inline("doc['positions.monthsWorked'].value != 0 && doc['positions.averageMonthLimit'].value > doc['positions.monthsWorked'].value")
) && +nq
.Script(sq => sq
.Inline("doc['positions.monthsWorked'].value != 0 && (doc['positions.averageMonthLimit'].value - 12) < doc['positions.monthsWorked'].value")
)) || (+nq
.Term(f => f.Positions.First().HasAverageLimitStatistic, false) && +nq
.DateRange(d => d
.Field(f => f.Positions.First().ExpirationDate)
.GreaterThan(DateTime.Now.Date)
.LessThan(DateTime.Now.Date.AddYears(1))
))
)
)
)
);
}
public class Person
{
public string FullName { get; set; }
public decimal TotalSalary { get; set; }
public List<Position> Positions { get; set; } = new List<Position>();
}
public class Position
{
public string Name { get; set; }
public bool IsCurrentPosition { get; set; }
public DateTime ExpirationDate { get; set; }
public int? MonthsWorked { get; set; }
public bool HasAverageLimitStatistic { get; set; } = false;
public int AverageMonthLimit { get; set; } = 0;
public decimal Salary { get; set; }
public string CompanyName { get; set; }
}
Based on the query criteria, only Person 1 and Person 3 are returned.

Linq Expression tree Any() issue

Hello I'm having trouble with an expression tree using the .Any() extension method.
Here's my code:
IQueryable<Book> querableBooks = Books.Values.AsQueryable<Book>();
ParameterExpression pe = Expression.Parameter(typeof(Book), "book");
MemberExpression props = Expression.Property(pe, "properties");
ParameterExpression propList = Expression.Parameter(typeof(List<BookProperty>), "properties");
var _test = Expression.Lambda<Func<List<BookProperty>, bool>>(operation, new ParameterExpression[] { propList });
var _Any = Expression.Call(typeof(Enumerable), "any", new Type[] { typeof(BookProperty) }, new Expression[] { propList });
Expression Lamba = Expression.Lambda(_Any, _props);
_test returns {properties => ((bookProperty.type.key == "lingerie") And (bookProperty.value == "1"))}
_Any returns {properties.Any()}
Lambda returns {book.properties => properties.Any()}
The Book class is like this:
public class Book : IBook
{
public int id { get; set; }
//Removed for clarity
public List<BookProperty> properties { get; set; }
}
An the BookProperty class:
public class BookProperty
{
public BookProperty()
{
value = "0";
}
public int id { get; set; }
public int bookId { get; set; }
public Book book { get; set; }
public int typeId { get; set; }
public BookPropertyType type { get; set; }
public string value { get; set; }
}
And BookPropertyType class:
public class BookPropertyType
{
public int id { get; set; }
public string groupe { get; set; }
public string key { get; set; }
public string label { get; set; }
public int order { get; set; }
public string editorType { get; set; }
public string unite { get; set; }
}
So I'm close to it, but I don't how to merge all this correctly to have a query like this
{book.propertie.Any(bookProperty => bookProperty.type.key == "lingerie") And (bookProperty.value == "1")}
Thanks for your help.
If I understand correctly, you are looking for expression like this:
Expression<Func<Book, bool>> bookPredicate = book => book.properties.Any(
bookProperty => bookProperty.type.key == "lingerie" && bookProperty.value == "1");
You can build it dynamically like this:
var book = Expression.Parameter(typeof(Book), "book");
var properties = Expression.PropertyOrField(book, "properties");
var bookProperty = Expression.Parameter(typeof(BookProperty), "bookProperty");
// bookProperty.type.key == "lingerie"
var conditionA = Expression.Equal(
Expression.PropertyOrField(Expression.PropertyOrField(bookProperty, "type"), "key"),
Expression.Constant("lingerie")
);
// bookProperty.value == "1"
var conditionB = Expression.Equal(
Expression.PropertyOrField(bookProperty, "value"),
Expression.Constant("1")
);
// bookProperty.type.key == "lingerie" && bookProperty.value == "1"
var condition = Expression.AndAlso(conditionA, conditionB);
// bookProperty => bookProperty.type.key == "lingerie" && bookProperty.value == "1"
var predicate = Expression.Lambda<Func<BookProperty, bool>>(condition, bookProperty);
// book.properties.Any(bookProperty => bookProperty.type.key == "lingerie" && bookProperty.value == "1")
var anyCall = Expression.Call(
typeof(Enumerable), "Any", new[] { typeof(BookProperty) },
properties, predicate
);
// book => book.properties.Any(...)
var bookPredicate = Expression.Lambda<Func<Book, bool>>(anyCall, book);

How to use condition for all children in Entity Framework

I have these classes:
public class product
{
public int Id { get; set; }
public string Title { get; set; }
public Store Store { get; set; }
public ICollection<Color> Colors { get; set; }
}
public class Color
{
public int Id { get; set; }
public string Name { get; set; }
public product Product { get; set; }
}
public class Store
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public ICollection<product> Products { get; set; }
}
And I have this list :
List<Store> Stores = new List<Store>
{
new Store { Id = 1, Name = "Lilo", City = "Teh",
Products = new List<product>
{
new product
{ Id = 1, Title = "Asus",
Colors = new List<Color> {
new Color { Id = 1, Name = "Blue"},
new Color { Id = 2, Name = "Orange"}
}
},
new product
{ Id = 2, Title = "Dell",
Colors = new List<Color> {
new Color { Id = 1, Name = "Yellow"},
new Color { Id = 2, Name = "Orange"},
new Color { Id = 3, Name = "Red"}
}
}
}
},
new Store{Id=2,Name="filo",City="san",
Products=new List<product>
{
new product{Id=3,Title="Asus",
Colors=new List<Color>{
new Color{Id=1,Name="Blue"},
new Color{Id=2,Name="Orange"}
}
},
new product{Id=4,Title="Dell",
Colors=new List<Color>{
new Color{Id=1,Name="Yellow"},
new Color{Id=2,Name="Lime"},
new Color{Id=3,Name="Red"}
}
}
}
}
};
I want to select all stores where Name ="Lilo" and products names is "Dell " and Color="Blue". I want do this in Entity Framework, not Linq.
I use this code but it doesn't work :
var test = Stores.Where(s => s.Name = "lilo" && s.Products.Where(p => p.Title == "Dell").FirstOrDefault().Title == "Dell" && s.Products.Where(c => c.Colors.Where(ct => ct.Name == "Blue").FirstOrDefault().Name = "Blue")).ToList();
How can I do this ?
Do this By Method Syntax :
var stlist = Stores.Where(s => s.Name.ToLower() == "lilo" && s.Products.Where(p => p.Colors.Any(c=>c.Name=="Blue") && p.Title == "Dell").FirstOrDefault().Title == "Dell").ToList();
Updated :
And Hopeless's Answers is (best answers):
var lslist2= Stores.Where(s => s.Name == "lilo" && s.Products.Any(p => p.Title == "Dell" && p.Colors.Any(c => c.Color.Name == "Blue"))).ToList();
And by Linq :
var test = (from s in Stores
from p in s.Products
from c in p.Colors
where s.Name=="Lilo" && p.Title=="Dell"&& c.Name=="Blue"
select s
).ToList();

Categories