使用Linq查询表达式语法基于索引和索引值联接两个数组

时间:2018-11-15 10:57:48

标签: c# linq

我想将两个数组连接起来,一个数组包含索引值,另一个数组包含索引位置。

string[] numStrings = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
int[] nums = new[] { 2, 32, 70 };

我想要的输出:

2   Two
32  Three-Two
70  Seven-Zero

我在下面的查询中尝试过

var strValuList = (from d in nums
                            from p in numStrings.Select((value, index) => new { value = value, index = index })
                            where p.index == d
                            select new { num = d, p.value}).ToList();

但仅返回

2两个

4 个答案:

答案 0 :(得分:1)

先尝试一下,然后再看答案:

提示:

IEnumerable<int> SplitNum(int num)
{
    while (num  > 0)
    {
        yield return num % 10;
        num /= 10;
    }
}

答案:

string[] numStrings = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
int[] nums = new[] { 2, 32, 70 };

(将鼠标悬停在黄色部分上以获得答案[一段时间后我将删除扰流板部分))

  

string []结果= nums.Select(n => string.Join(“-”,SplitNum(n).Reverse()。Select(i => numStrings [i])))。ToArray();

  DotNetFiddle example

答案 1 :(得分:0)

string[] numStrings = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
int[] nums = new[] { 2, 32, 70 };

var dict = new Dictionary<int, string>();

foreach(var n in nums)
{
    var str = string.Join("-", n.ToString().Select(s => numStrings[Convert.ToInt32(s.ToString())]));
    dict[n] = str;
}

答案 2 :(得分:0)

我解决它没有太多复杂性。谢谢@Jeroen Mostert的建议

string[] numStrings = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
int[] nums = new[] { 2, 32, 70 };
(from d in nums
select new
{
    num = d,
    parts = d.ToString().Select(o=> Convert.ToInt32(o.ToString())),
    parts2 = d.ToString().Select(o => numStrings[Convert.ToInt32(o.ToString())]),
    parts3 = string.Join("-",d.ToString().Select(o => numStrings[Convert.ToInt32(o.ToString())]).ToArray())
}).Dump();

LinqPad中的输出: enter image description here

答案 3 :(得分:0)

这是许多方法之一:

void Main()
{
    string[] numStrings = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
    int[] nums = new[] { 2, 32, 70 };

    Func<int, string> numToWord = (x) => {
        List<string> words = new List<string>();
        do {
            words.Add( numStrings[x%10] );
            x /= 10;
        } while (x > 0);
        var w = words.Reverse<string>();
        return string.Join("-",w);
    }; 

    var result = nums.Select(n => numToWord(n));

    foreach (var element in result)
    {
        Console.WriteLine(element);
    }
}