Ali
Ali

Reputation: 71

Can I store LINQ query result in an array?

This is the code using LINQ, it stores the values into list

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);
        }

Can it not be stored into Array? Where I can display only item I want. Just like here the output is {Index=, Value=, Token=} Meanwhile I want the output that be of just "Value" "Token" index not needed.

Upvotes: 0

Views: 1903

Answers (1)

Marko Juvančič
Marko Juvančič

Reputation: 5890

You can use ToArray instead. But List gives you the desired array functionality already, you can access an item by its index.

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

EDIT: as I can see from your comments, you need this:

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

Upvotes: 1

Related Questions