如何将此foreach循环转换为Linq代码? [英] How to convert this foreach loop into Linq code?

查看:103
本文介绍了如何将此foreach循环转换为Linq代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Linq的新手,我想修改旧的c#代码以使用Linq. 此代码的想法是选择未设置的所有表,并且引用的字段PrimaryTable等于"myTable"

I am new one with Linq and I would like to modify my old c# code to use Linq. The idea of this code to select all tables where it's not set and reference’s field PrimaryTable equal "myTable"



foreach (Table table in dbServer.Tables)
            {
                if (!table.IsSet)
                {
                    foreach (Reference refer in table.References)
                    {
                        if (refer.PrimaryTable == "myTable")
                        {
                            tables.Add(table);
                        }
                    }
                }
            }

深入互联网后,我得到了这段代码

After digging in internet I have got this code



var q = from table in dbServer.Tables
                    let refers = from refer in table.References
                                 where refer.PrimaryTable == "myTable"
                                 select refer.ForeignTable
                    where refers.Contains(table.Name)
                    select table;

但是它根本不起作用,我需要您的帮助才能使其起作用.

But it does not work at all and I need your help to make it works.

提前谢谢.

推荐答案

var tables = dbServer.Tables
    .Where(t => !t.IsSet)
    .SelectMany(t => t.References)
    .Where(r => r.PrimaryTable == "myTable")
    .ToList();

假设表格是List<T>

正如评论所指出的,这与原始内容不同-看起来您真正想要的是这样的:

As the comment points out, this isn't the same as the original - it looks like what you actually want is this:

var tables = dbServer.Tables
    .Where(t => !t.IsSet && t.References.Any(r => r.PrimaryTable == "myTable"))
    .ToList();

这将为您提供所有具有引用的表,这些引用的主表为"myTable",并假设只有一个匹配的引用表.否则,您可能会多次添加同一张表.

This will give you all the tables which have a reference whose PrimaryTable is 'myTable' which assumes that there will only be one matching reference table. Otherwise you could have the same table added multiple times.

这篇关于如何将此foreach循环转换为Linq代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆