带有不同where条件的c# linq列表

本文关键字:linq 列表 条件 where | 更新日期: 2023-09-27 18:10:51

private void getOrders()
{
    try
    {
        //headerFileReader is assigned with a CSV file (not shown here).
        while (!headerFileReader.EndOfStream)
        {
           headerRow = headerFileReader.ReadLine();
           getOrderItems(headerRow.Substring(0,8))
        }
    }
}
private void getOrderItems(string ordNum)
{
    // lines is an array assigned with a CSV file...not shown here.
    var sorted = lines.Skip(1).Select(line => 
        new 
        {
            SortKey = (line.Split(delimiter)[1]),
            Line = line
        })
        .OrderBy(x => x.SortKey)
        .Where(x => x.SortKey == ordNum);
    //Note ordNum is different every time when it is passed.
    foreach (var orderItems in sorted) {
        //Process each line here.
    }
}
上面是我的代码。我所做的是,对于headerFile中的每个订单号,我处理详细信息。我想只搜索那些特定于订单号的行。上面的逻辑工作得很好,但是对于每个订单号,它读起来都是where子句,这是根本不需要的,并且会延迟流程。

我基本上想有getOrderItems下面的东西,但我不能得到作为排序不能传递,但我认为它应该是可能的??

private void getOrderItems(string ordNum)
{
    // I would like to have sorted uploaded with data elsewhere and I pass it this function and reference it by other means but I am not able to get it.
    var newSorted = sorted.Where(x => x.SortKey == docNum);
    foreach (var orderItems in newSorted) {
        //Process each line here.
    }
}

请建议。

更新:感谢您的回复&但我的主要问题是我不想每次都创建列表(就像我在代码中显示的那样)。我想要的是第一次创建列表,然后只在列表中搜索一个特定的值(这里显示的是docNum)。请建议。

带有不同where条件的c# linq列表

对输入行进行预处理并构建一个字典可能是一个好主意,其中每个不同的排序键映射到行列表。构建字典是O(n),之后你得到恒定时间的O(1)查找:

// these are your unprocessed file lines
private string[] lines;
// this dictionary will map each `string` key to a `List<string>`
private Dictionary<string, List<string>> groupedLines;
// this is the method where you are loading your files (you didn't include it)
void PreprocessInputData()
{
     // you already have this part somewhere
     lines = LoadLinesFromCsv(); 
     // after loading, group the lines by `line.Split(delimiter)[1]`
     groupedLines = lines
        .Skip(1)
        .GroupBy(line => line.Split(delimiter)[1])
        .ToDictionary(x => x.Key, x => x.ToList());
}
private void ProcessOrders()
{
    while (!headerFileReader.EndOfStream)
    {
        var headerRow = headerFileReader.ReadLine();
        List<string> itemsToProcess = null;
        if (groupedLines.TryGetValue(headerRow, out itemsToProcess))
        {
            // if you are here, then
            // itemsToProcess contains all lines where
            // (line.Split(delimiter)[1]) == headerRow
        }
        else
        {
             // no such key in the dictionary
        }
    }
}

下面的方法会让你更有效率。

var sorted = lines.Skip(1)
    .Where(line => (line.Split(delimiter)[1] == ordNum))
    .Select(
        line => 
            new 
            {
                SortKey = (line.Split(delimiter)[1]),
                Line = line
            }
    )
    .OrderBy(x => x.SortKey);