The title sounds like nonsense, but the example below will hopefully help.

Trying to write a big LINQ statement where, given a list of strings and a list of integers, it can gather a list of all of the characters in that list into one. Example:

indices:

{2,4}

possible:

{"hello","world"}

should give me:

{'l','o','r','d'}

from indices 2 and 4 in each string.

I think I'm a bit off, but here's a messy statement I was working on to give something to work from/correct:

var lettersToCheckOut = possible.Select(s => s.ToCharArray()).Select((c, index) => new
                        {
                            let = c,
                            ind = index
                        }).Where(c => indices.Contains(c.ind)).Select(c => c.let);
有帮助吗?

解决方案

Something like that?

var chars = indices.SelectMany(i => words.Where(w => i < w.Length)
                                         .Select(w => w[i])).ToList();
Console.WriteLine(string.Join(",", chars)); // lrod

The logic is as follows:

  • For each index, I would like to go over all of the possible words, and gather characters.

  • I must check, first, that the index is within the range of the current word.

  • From each word, I take the character indexed as the current index.

  • Using the SelectMany method, I get a collection of characters rather than a collection of IEnumerable<char>.

You can swap between indices and words to get the characters in different order:

var chars = words.SelectMany(w => indices.Where(i => i < w.Length)
                                         .Select(i => w[i])).ToList();
Console.WriteLine(string.Join(",", chars)); // lord

其他提示

I know the question has already been answered, but here's an alternate solution using Linq's query comprehension syntax. I personally find it more elegant, and am sharing it in case others do as well:

        var words = new[] { "Hello", "World" };
        var indexes = new[] { 2, 4 };

        //{ 'l', 'o', 'r', 'd' }
        var output = 
            from word in words
            from index in indexes
            where word.Length > index
            select word[index];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top