名字和名字的数组连接

时间:2012-05-11 01:30:31

标签: c# arrays

我有以下程序,我想要做的是从2个文本文件中加入我的名字列表,在第一个文本文件中我有名字,在secont姓氏中,我正在尝试加入他们。然后,我试图列出文件的所有组合,即名字是标记和迈克,姓氏是威尔逊和沃森,我想让迈克沃森和迈克威尔逊

    TextReader sr = new StreamReader(textBox1.Text);
        TextReader sr2 = new StreamReader(textBox2.Text);
        string contents = sr.ReadToEnd();
        string contents2 = sr2.ReadToEnd();
        string[] myArray = { contents };
        string[] myArray2 = { contents2 };
        foreach (string element1 in myArray)
        {
            foreach (string element2 in myArray2)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append(element1);
                sb.Append(" " + element2);
                Debug.WriteLine(sb.ToString());

                string str = sb.ToString();
                Debug.WriteLine(str);

                //MessageBox.Show(sb.ToString);
            }
        }

最终结果应该是来自file1的Mike Smith:mike,file2:smith

感谢您的帮助

使用上述答案的组合我得出了这个答案,分割文本文件时'\ r'是至关重要的,因为文本是从Windows 2003中读取的(我不确定win 7或2008的结果是什么使用内置数组是好的,但我尝试从文件系统运行它时得到完全不同的结果,添加'\ r'修复了 请看这篇文章

In C#, what's the difference between \n and \r\n?

TextReader sr = new StreamReader(textBox1.Text);
        TextReader sr2 = new StreamReader(textBox2.Text);
        string contents = sr.ReadToEnd();
        string contents2 = sr2.ReadToEnd();
        string[] firstNames = contents.Split(new Char[] { '\r','\n',' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
        string[] lastNames = contents2.Split(new Char[] { '\r','\n',' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
        var fullnames =
                    from fn in firstNames
                    from ln in lastNames
                    select new { Fullname = fn + " " + ln };

        foreach (var person in fullnames)
        {
            Debug.WriteLine(person.Fullname);
            //MessageBox.Show(person.Fullname);
        }

8 个答案:

答案 0 :(得分:4)

<强> LINQ

这会将第一个名字加上第一个姓氏

string[] joinednames = myArray.Zip(myArray2, (x, y) => x + " " + y).ToArray();

如果您想加入first firstname with all lastnamesecond firstname with all lastnames以及so on,请使用此

string[] joinednames = myArray.Select(x => myArray2.Select(y => 
                       x + " " + y)).SelectMany(x => x).ToArray();

假设第一个列表包含firstnames

"Mark""Marry"

,第二个列表包含姓氏

"Watson""Wilson"

第一个Snipppet将提供

"Mark Watson""Marry Wilson"

第二个代码段将提供

"Mark Watson""Mark Wilson""Marry Watson""Marry Wilson"

我认为第二段是你需要的。

答案 1 :(得分:1)

您当前的代码已关闭。

TextReader sr = new StreamReader(textBox1.Text); 
TextReader sr2 = new StreamReader(textBox2.Text); 

string contents = sr.ReadToEnd(); 
string contents2 = sr2.ReadToEnd(); 

string[] myArray = contents.Split(new Char [] {' ', ','}, StringSplitOptions.RemoveEmptyEntries); 
string[] myArray2 = contents2.Split(new Char [] {' ', ','}, StringSplitOptions.RemoveEmptyEntries); 
System.Text.StringBuilder sb = new System.Text.StringBuilder();

var joinednames = myArray.Zip(myArray2, (x, y) => x + " " + y).ToList();

foreach (string str in joinednames)
{
    Debug.WriteLine(str);
}

您可能应该在名称之间添加一些其他分隔符。

编辑:我将我的答案与Nikhil's合并,并在VS中进行了一些测试。

答案 2 :(得分:1)

我同意mgnoonan的说法,你的主要问题是你没有正确地将你的名字列表解析出来。使用他的方法将名称转换为数组。但是,一旦你有了它们,我就会喜欢Nikhil的LINQ解决方案的优雅,它将这两个阵列结合起来。使用它们。

修改 以下示例

TextReader sr = new StreamReader(textBox1.Text); 
TextReader sr2 = new StreamReader(textBox2.Text); 

string contents = sr.ReadToEnd(); 
string contents2 = sr2.ReadToEnd(); 

string[] myArray = contents.Split(new Char [] {' ', ','}); 
string[] myArray2 = contents2.Split(new Char [] {' ', ','}); 

string[] joinednames = myArray.Zip(myArray2, (x, y) => x + " " + y).ToArray();

foreach(string element in joinednames)
{
    Debug.WriteLine(element);
}

答案 3 :(得分:1)

此答案仅基于您对问题所做的评论。根据您的评论,如果您要创建阵列的所有可能组合,这里是没有LINQ的解决方案

string[] firstNames = {"Mark", "Mike" };
string[] lastNames = {"Watson", "Wilson" };
IList<string> allNameCombinations = new List<string>();

foreach (string firstname in firstNames)
{
    foreach (string lastname in lastNames)
         allNameCombinations.Add(firstname + " " + lastname);
}

string[] allNames = allNameCombinations.ToArray();

输出数组将具有以下元素

Mark Watson
Mark Wilson
Mike Watson
Mike Wilson

答案 4 :(得分:0)

虽然其他答案很有帮助,但他们并没有解释你哪里出错了。原始代码的问题是这些陈述:

string[] myArray = { contents }; 
string[] myArray2 = { contents2 }; 

第一个语句使用一个元素创建一个数组;该元素是对contents变量引用的相同字符串的引用。同样,myArray2是一个单个元素等于contents2的数组。

通过拆分行分隔符字符来创建数组:

string[] myArray = contents.Split(new Char [] {'r', 'n'}, StringSplitOptions.RemoveEmptyEntries);    
string[] myArray2 = contents2.Split(new Char [] {'r', 'n'}, StringSplitOptions.RemoveEmptyEntries); 

并将它们合并为Nikhil Agrawal建议的;但是,您可能会发现查询理解语法更容易理解:

IEnumerable<string> fullNames = 
    from firstName in myArray
    from lastName in myArray2
    select firstName + " " + lastName

或者,要颠倒产品的顺序:

IEnumerable<string> fullNames = 
    from lastName in myArray2
    from firstName in myArray
    select firstName + " " + lastName

或者,如果您不想使用linq:

foreach (string firstName in myArray)
    foreach (string lastName in myArray2)
    {
        string fullName = firstName + " " + lastName;
        // do something with the fullName here
    }

答案 5 :(得分:0)

您需要更好地读取文件中的条目(读取多行,每行多个条目,空格或逗号分隔):

var firsts = File.ReadAllLines(textBox1.Text).SelectMany(n => n.Split(new Char [] {' ', ','}));
var lasts = File.ReadAllLines(textBox2.Text).SelectMany(n => n.Split(new Char [] {' ', ','}));

然后你可以像其他答案那样建议:

var fullNames = firsts.Zip(lasts, (f, l) => f + " " + l).ToArray();

注意:确保使用using System.Linq;

导入LINQ

答案 6 :(得分:0)

阅读你的问题的评论,你想列出组合名字和姓氏的所有可能性,不是吗?

你可以试试这个:

var fullnames = 
        from fn in firstNames
        from ln in lastNames
        select new { Fullname = fn + " " + ln };

foreach(var person in fullnames) {
    Console.WriteLine (person.Fullname);
}

完整代码:

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

public class Test
{
        public static string[] firstNames = {"Mark", "Mike" };
        public static string[] lastNames = {"Watson", "Wilson"};

        public static void Main (string[] args)
        {

                var fullnames = 
                        from fn in firstNames
                        from ln in lastNames
                        select new { Fullname = fn + " " + ln };

                foreach(var person in fullnames) {
                     Console.WriteLine (person.Fullname);
                }

      }
}

输出:

Mark Watson
Mark Wilson
Mike Watson
Mike Wilson

演示代码:http://ideone.com/ei6vh

答案 7 :(得分:0)

您的代码在这些方面有问题:

string contents = sr.ReadToEnd();
string contents2 = sr2.ReadToEnd();

// arrays don't automatically split string content
string[] myArray = { contents };
string[] myArray2 = { contents2 };

你应该这样做:

string contents = sr.ReadToEnd();
string contents2 = sr2.ReadToEnd();

// arrays don't automatically split file content
string[] myArray = contents.Split('\n');
string[] myArray2 = contents2.Split('\n');

或者更好的是,将它拆分为读者:

string[] myArray = sr.ReadToEnd().Split('\n');
string[] myArray2 = sr.ReadToEnd().Split('\n');

请注意,某些文本文件的行分隔符不一致,有些使用\r\n的组合(大多数来自Windows应用的文本文件),有些只使用\n,我还没有看到使用\r的文本文件仅用于行分隔符。

请改为:

string[] myArray = 
    sr.ReadToEnd().Split (new[]{"\r\n", "\n", "\r"}, StringSplitOptions.None);

string[] myArray2 = 
    sr.ReadToEnd().Split (new[]{"\r\n", "\n", "\r"}, StringSplitOptions.None);