简体   繁体   English

如何使用 linq c# 从另一个列表优化嵌套循环和过滤

[英]How do optimize nested loop and filter from another list using linq c#

I am trying to filter a flattened nested loop and filter from another list.我正在尝试过滤一个展平的嵌套循环并从另一个列表中过滤。 So below is what I have been able to do.所以下面是我能够做的。 I tried this approach but when I run the query it does not save anything in the database.我尝试过这种方法,但是当我运行查询时,它不会在数据库中保存任何内容。 I need help to check and ignore existing records (same MemberId and Description) in the Tasklist table.我需要帮助来检查和忽略 Tasklist 表中的现有记录(相同的 MemberId 和 Description)。

var addedtop = from a in db.TaskLists select new {a.MemberId,a.Description};
var membtasks = from m in members
                        from n in tasks
                        select new { m, n };

       
        TaskList taskList = new TaskList();
        foreach (var item in membtasks)
        {
            var exist = db.TaskLists.Where(a => a.Description == item.n && a.MemberId == item.m);
            if(exist == null)
            {    
            taskList .Description = item.n;
            taskList .MemberId = item.m;
            db.taskList .Add(taskList );
            db.SaveChanges();

            }
       }
        return Redirect(url);

The problem is exists will never be null .问题null exists The line var exist = db.TaskLists.Where(a => a.Description == item.n && a.MemberId == item.m);var exist = db.TaskLists.Where(a => a.Description == item.n && a.MemberId == item.m); returns an IQueryable that describes your query but hasn't actually executed against the database yet.返回一个IQueryable来描述您的查询,但实际上还没有对数据库执行。

Try changing the line to:尝试将行更改为:

var exist = db.TaskLists.Where(a => a.Description == item.n && a.MemberId == item.m).SingleOrDefault();

This executes the query and checks if there is a single item that satisfies your query.这将执行查询并检查是否有满足您查询的单个项目。 If there is no result at all the query returns null which will execute the code inside your if statement.如果根本没有结果,查询将返回null ,它将执行 if 语句中的代码。

Your statement has not been executed query, you can change Where to Any like this:您的语句尚未执行查询,您可以像这样将 Where 更改为 Any:

var exist = db.TaskLists.Any(a => a.Description == item.n && a.MemberId == item.m);

Any function that returns data type is bool Any返回数据类型为bool的 function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM