【问题标题】:Can I store LINQ query result in an array?我可以将 LINQ 查询结果存储在数组中吗?
【发布时间】:2016-03-26 12:46:50
【问题描述】:

这是使用 LINQ 的代码,它将值存储到列表中

string StringRegex = "\"(?:[^\"\\\\]|\\\\.)*\"";

        Dictionary<string, string> dictionaryofString = new Dictionary<string, string>()
        {
            {"String", StringRegex}
        };

 var matches = dictionaryofString.SelectMany(a => Regex.Matches(input,a.Value)
        .Cast<Match>()
        .Select(b =>
                new
                {
                    Index = b.Index,
                    Value = b.Value,
                    Token = a.Key
                }))
        .OrderBy(a => a.Index).ToList();
        for (int i = 0; i < matches.Count; i++)
        {
            if (i + 1 < matches.Count)
            {
                int firstEndPos = (matches[i].Index + matches[i].Value.Length);
                if (firstEndPos > matches[(i + 1)].Index)
                {
                    matches.RemoveAt(i + 1);
                    i--;
                }
            }
        }
foreach (var match in matches)
        {
            Console.WriteLine(match);
        }

不能存入Array吗?我只能显示我想要的项目。就像这里的输出是 {Index=, Value=, Token=} 同时我希望输出只是不需要“价值”“令牌”索引。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    您可以改用ToArray。但是List 已经为您提供了所需的数组功能,您可以通过索引访问项目。

    var exampleQuery = select c from componentsDemo;
    var list = exampleQuery.ToList();
    var secondElement = list[1]; // <- demo only, there could be an exception thrown, if there's less than two elements in the list
    

    编辑:正如我从你的 cmets 看到的,你需要这个:

    foreach (var match in matches)
    {
       Console.WriteLine(match.Value + ", " + match.Token); 
    }
    

    【讨论】:

    • 这是我第一次使用 ToList 函数。并且无法控制输出。例如,当前输出是 {Index=0, Value="asd", Token=String"} 我希望输出是:"asd" Token
    • Marko,它工作了,但它只显示值字段,它也可以与令牌字段连接吗?
    • 是的 match.Value + match.Token
    • @Marko Juvančič“或此”选项不适用于 OP,建议类似,还需要索引以进行进一步处理
    • 是的,你是对的。我没有看到那部分代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 2023-03-20
    • 2021-12-28
    • 2012-03-13
    • 2012-11-05
    • 1970-01-01
    相关资源
    最近更新 更多