How to convert this foreach loop into Linq code?

前端 未结 4 570
醉酒成梦
醉酒成梦 2021-01-03 11:21

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 PrimaryTab

4条回答
  •  佛祖请我去吃肉
    2021-01-03 11:53

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

    Assuming tables is a List

    EDIT: 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();
    

    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.

提交回复
热议问题