简体   繁体   English

使用带有逗号分隔 ID 的 LINQ 从 SQL 获取所有数据

[英]Getting all Data from SQL using LINQ with comma-separated IDs

I do have a string of Empids separated by comma like:我确实有一串用逗号分隔的 Empids,例如:

EMpID:"2007,2008,2002,1992,1000,2108,1085

and I need to retrieve the records of all those specified employees using LINQ query.我需要使用 LINQ 查询检索所有指定员工的记录。 I tried it with looping but I need to get that in efficient and faster way.我尝试了循环,但我需要以高效和更快的方式实现它。

Here goes what i did using looping.这是我使用循环所做的。

string[] EMpID_str = LeaveDictionary["EMpID"].ToString().Split(',');

for (int i = 0; i < EMpID_str.Length; i++)
            {
                EMpID = Convert.ToInt32(EMpID_str[i]);

               //Linq to get data for each Empid goes here
             }

But What I need is to use single LINQ or Lambda query to retrieve the same.Without looping但我需要的是使用单个 LINQ 或 Lambda 查询来检索相同的查询。没有循环

If the Ids that you want to fetch are numbers, not strings, then you should not convert the string to an array of strings, but to a sequence of numbers:如果要获取的 Id 是数字,而不是字符串,则不应将字符串转换为字符串数组,而是转换为数字序列:

IEnumerable<int> employeeIdsToFetch = LeaveDictionary["EMpID"].ToString()
    .Split(',')
    .Select(splitText => Int32.Parse(splitText));

To fetch all employees with thees Ids:要获取所有具有这些 ID 的员工:

var fetchedEmployees = dbContext.Employees
    .Where(employee => employeeIdsToFetch.Contains(employee.Id))
    .Select(employee => new
    {
         // Select only the employee properties that you plan to use:
         Id = employee.Id,
         Name = employee.Name,
         ...
    });

First convert your,(comma) separated empId to string array like below:首先将您的,(逗号)分隔的 empId 转换为字符串数组,如下所示:

var empArr = EmpId.split(','); 
var employeesResult = emplyeeList.Where(x => empArr.contains(x.EmpId.ToString()));

I hope, it will help someone.我希望,它会帮助某人。

You can use the Expression class to build a Func<int, bool> from your string and use it with the Where methode:您可以使用Expression class 从您的字符串构建Func<int, bool>并将其与Where方法一起使用:

var str = "2,5,8,9,4,6,7";

var para = Expression.Parameter(typeof(int));

var body = str.Split(",")
    .Select(s => int.Parse(s))
    .Select(i => Expression.Constant(i))
    .Select(c => Expression.Equal(para, c))
    .Aggregate((a, b) => Expression.Or(a, b));

Func<int, bool> func = Expression.Lambda<Func<int, bool>>(body, para).Compile();

and if you this solution to work with linq to SQL just dont compile the expression at the end and let the linq to SQL engine compile it to an efficent SQL expression. and if you this solution to work with linq to SQL just dont compile the expression at the end and let the linq to SQL engine compile it to an efficent SQL expression.

Instead of the Aggregate Method (which will produce an expression with linear complexity) one could use an divide and conquer approach to fold the values into one value.可以使用分而治之的方法将值折叠成一个值,而不是使用Aggregate方法(这将产生具有线性复杂性的表达式)。

For example with this class:例如,使用此 class:

public static class Helper
{
    public static T EfficientFold<T>(this List<T> list, Func<T, T, T> func)
    {
        return EfficientFold(list, 0, list.Count, func);
    }

    private static T EfficientFold<T>(List<T> list, int lowerbound, int upperbound, Func<T, T, T> func)
    {
        int diff = upperbound - lowerbound;
        var mid = lowerbound + diff / 2;

        if (diff < 1)
        {
            throw new Exception();
        }
        else if (diff == 1)
        {
            return list[lowerbound];
        }
        else
        {
            var left = EfficientFold(list, lowerbound, mid, func);
            var right = EfficientFold(list, mid, upperbound, func);

            return func(left, right);
        }
    }
}

and then we can do然后我们可以做

var body = str.Split(",")
    .Select(s => int.Parse(s))
    .Select(i => Expression.Constant(i))
    .Select(c => Expression.Equal(para, c))
    .ToList()
    .EfficientFold((a, b) => Expression.Or(a, b));

which gives the evaluation a complexity of log(n) .这使评估的复杂性为log(n)

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

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