在C#中加入两个列表<string>

时间:2016-10-29 15:35:13

标签: c#

我有两个不同长度的字符串列表。例如

List <string> Mksnos={"Toyota",
                     "Honda is Good",
                     "Innova is very good" }


List <string> GdsDscr={"Toyota is a very good brand
                       and it is costly",
                       "The carmaker's flagship sedan is now here in its hybrid avatar. It is brought to... The Honda Accord Hybrid has been launched in India" }

enter image description here

这样的结果是我会给出任何建议吗?

2 个答案:

答案 0 :(得分:1)

如果两个列表的索引相同,则可以执行以下操作:

static void Main(string[] args)
{
    List<string> Mksnos = new List<string>()
    {
        "Toyota",
        "Honda is Good",
        "Innova is very good"
    };

    List<string> GdsDscr = new List<string>()
    {
        "Toyota is a very good brand and it is costly",
        "The carmaker's flagship sedan is now here in its hybrid avatar. It is brought to... The Honda Accord Hybrid has been launched in India"
    };

    var joinedLists = new Dictionary<string, string>();

    for (int i = 0; i < Mksnos.Count(); i++)
    {
        var nksnosValue = Mksnos[i];
        var gdsDscr = GdsDscr.Count() > i ? GdsDscr[i] : string.Empty;

        joinedLists.Add(nksnosValue, gdsDscr);
    }

    foreach (var joined in joinedLists)
    {
        Console.WriteLine($"{joined.Key}: {joined.Value}");
    }

    Console.ReadKey();
}

答案 1 :(得分:0)

Zip Linq功能基本上可以完全达到您之后的效果 - 尽管它输出的数量可以达到最小的数量。

https://msdn.microsoft.com/en-us/library/dd267698(v=vs.110).aspx

但相反,我们可以像这样填写第二个列表:

using System;
using System.Linq;
using System.Collections.Generic;

List<string> Mksnos= { "Toyota", "Honda is Good", "Innova is very good" };
List<string> GdsDscr= { "Toyota is a very good brand and it is costly",
                       "The carmaker's flagship sedan is now here in its hybrid avatar. It is brought to... The Honda Accord Hybrid has been launched in India" };

var numberOfMissingValues = Math.Max(Mksnos.Count - GdsDscr.Count, 0);
var paddedGdsDscr = GdsDscr.Concat(Enumerable.Range(0, numberOfMissingValues).Select(i => " ")).ToList();

var lines = Mksnos.Zip(paddedGdsDscr, (make, comment) => $"{make}: {comment}");

foreach (var line in lines)
{
    Console.WriteLine(line);
}

Console.ReadKey();

如果您要查找多个列表(对于某些固定号码),您可以执行以下操作:

var comments = firstComments.Zip(secondComments, (b, c) => $"{b} - {c}")
var outLines = makes.Zip(comments, (make, comment) => $"{make}: {comment}");

显然,如果没有更详细的规格,围绕不匹配的列表大小做什么的问题是无法回答的!