jaabh
jaabh

Reputation: 1004

Linq Where clause to generate List based on results of a different List

I am trying to generate a List<Object> using Where clause with properties from a different List<Object>. I know that I could use a .Include(), similar to a SQL join if I were using Entity Framework but I am not using Entity Framework so I don't think it would work. I have:

List<Problem> problems = MethodToCallDbAndGenerateList();  //ado.net
problems = problems.Where(x => x.Property1 == "value").ToList();
//remaining logic

List<Solved> solved = MethodToCallDb()
                      .Where(x => x.SolvedId == problems.ProblemId)
                      .ToList();
             //error happens in Where(...problems.ProblemId);
         //List<Problem> does not contain a definition for ProblemId

The error says the List<Problem> does not contain ProblemId but I do have that property in my class. So I am unsure of why I am getting that error.

How can I generate my List<Solved> based on filtered results from

.Where(x => x.SolvedId == problems.SolvedId);

Upvotes: 0

Views: 469

Answers (1)

NetMage
NetMage

Reputation: 26917

Using LINQ to Objects, you can use the Enumerable.Join method to create a join between two List<T>s and just return the matching members:

List<Problem> problems = MethodToCallDbAndGenerateList()
                            .Where(x => x.Property1 == "value")
                            .ToList();

List<Solved> solved = MethodToCallDb()
                      .Join(problems, s => s.SolvedId, p => p.ProblemId, (s,p) => s)
                      .ToList();

However, if there are a lot of problems and solved, or if you frequently check the same list of problems, or if you are only creating problems to use in the join, you'd be better off creating a HashSet:

var problemIDs = problems.Select(p => p.ProblemId).ToHashSet();

List<Solved> solved = MethodToCallDb()
                      .Where(s => problemIDs.Contains(s.SolvedId))
                      .ToList();

NOTE: If you are only creating problems to use in the join, better to skip creating the List<Problem> and just do:

var problemIDs = MethodToCallDbAndGenerateList()
                    .Where(x => x.Property1 == "value")
                    .Select(p => p.ProblemId)
                    .ToHashSet();

Upvotes: 1

Related Questions