LINQ查询:使用Any检索列表

时间:2015-11-02 12:34:00

标签: c# linq

我有两张桌子。联系表和客户端表。 ContactID是客户端表中的外键。 我有一个返回联系人列表的查询。我想在第一个联系人列表中找到client.contactid所有客户端的单独列表。我想我现在可以使用Any方法确定如何。谢谢。使用LINQ to EF

 List<Contact> contacts = GetContactByCompany().ToList();

有一些事情

List<Client> = from client in Client.Any(client => contacts.ID.Contains(client.ContactID))

4 个答案:

答案 0 :(得分:2)

看起来你正在寻找像这样的东西

@Bean
    protected ConversionService neo4jConversionService() throws Exception {
        ConversionService conversionService = super.neo4jConversionService();
        ConverterRegistry registry = (ConverterRegistry) conversionService;

        registry.removeConvertible(Date.class, String.class);
        registry.removeConvertible(String.class, Date.class);
        registry.removeConvertible(String.class, Character.class);
        registry.removeConvertible(Character.class,String.class);
        // add converters
        registry.addConverter(new DateTimeToStringConverter());
        registry.addConverter(new StringToDateTimeConverter());
        registry.addConverter(new StringToCharConverter());
        registry.addConverter(new CharToStringConvertor());
        return conversionService;
    }

var clients = Client.Where(client => contacts.Any(contact => contact.ID == client.ContactID)).ToList();

答案 1 :(得分:1)

可能的解决方案

从提取的第一个联系人列表中获取联系人ID列表

List<int> ContactIdList = ContactList.Where(x=>x.Id).ToList()

获取ContactId的所有客户端和过滤器,它们是上面提取的ContactIds列表的一部分

List<Client> FilteredClientList = ClientList.Where(x=>ContactIdList.Contains(x.ContactId)).ToList()

答案 2 :(得分:1)

现在你说它是EF :(

List<Contact> contacts = GetContactByCompany().ToList();
var contactIds = contacts.Select( c => c.ContactID ).Distinct();
var clients = ctx.Clients.Where( c => contactIds.Contains( c.ContactID ) );

PS:这不会超出指定后端的参数计数限制(即:在MS SQL中,它最多可以使用2100个ID)。

答案 3 :(得分:0)

var clients = contacts.Select( c => c.Client ); // Distinct() may be needed

使用MS SQL服务器示例数据库Northwind进行采样:

var orders = Orders.Where (o => o.ShipCountry == "USA");
var customers = orders.Select (o => o.Customer).Distinct();

当客户实现时(foreach,ToList()...)这是发送给服务器的SQL:

-- Region Parameters
DECLARE @p0 NVarChar(1000) SET @p0 = 'USA'
-- EndRegion
SELECT DISTINCT [t1].[CustomerID], [t1].[CompanyName], [t1].[ContactName], [t1].[ContactTitle], [t1].[Address], [t1].[City], [t1].[Region], [t1].[PostalCode], [t1].[Country], [t1].[Phone], [t1].[Fax]
FROM [Orders] AS [t0]
INNER JOIN [Customers] AS [t1] ON [t1].[CustomerID] = [t0].[CustomerID]
WHERE [t0].[ShipCountry] = @p0