我有一个字符串数组[2]如下:
1st Array 2nd Aray
"100101" "Testing123"
"100102" "Apple123"
"100101" "Dog123"
"100104" "Cat123"
"100101" "Animal123"
如果第一个数组中的元素匹配,我想连接第二个数组的所有元素。
例如,匹配的第一个数组的元素是“100101”,“100101”和“100101”。因此,具有相应第二个数组的连接值的字符串如下:
"Testing123 Dog123 Animal123"
如何才能优雅地实现这一目标?
答案 0 :(得分:2)
我是这样做的:
var results =
array1
.Zip(array2, (x1, x2) => new { x1, x2 })
.ToLookup(x => x.x1, x => x.x2)
.Select(x => new { x.Key, Value = String.Join(" ", x), });
我得到了这个结果:
如果你需要以不同的方式提取结果,那么根据我的方法来获得你需要的东西并不是太难。
答案 1 :(得分:1)
您可以使用GroupBy
:
var strings = array1.Select((s,index) => new{ s, index })
.GroupBy(x => x.s)
.Select(g =>
string.Join(" ", g.Select(x => array2.ElementAtOrDefault(x.index))));
foreach(string s in strings)
Console.WriteLine(s);
如果只想连接第一个数组中重复的字符串,请添加Where
:
// ...
.GroupBy(x => x.s)
.Where(g => g.Count() > 1)
// ...
答案 2 :(得分:0)
var indices = array1.Select((i, s) => new {Index = i, Str = s})
.Where(e => e.Str == "100101")
.Select(e => e.Index);
string result = string.Join(" ", array2.Select((i, s) => new {Index = i, Str = s})
.Where(e => indices.Contains(e.Index))
.Select(e => e.Str));
答案 3 :(得分:0)
假设两个数组的长度相同,这应该可以为您提供所需的输出。
var array1 = new[] {"100101", "100102", "100101", "100104","100101" };
var array2 = new[] { "Testing123", "Apple123", "Dog123","Cat123", "Animal123" };
var result = new Dictionary<string, string>();
for (int i = 0; i < array1.Length; i++)
{
// if the value has been found before
if( result.ContainsKey( array1[i] ) ) {
result[array1[i]] += " " + array2[i]; // append to existing "matched" entry
}
else {
result.Add(array1[i], array2[i]); // add new unique value
}
}
答案 4 :(得分:0)
您可以压缩这两个数组,因为它们的大小相同。然后按第一个数组值对元素进行分组。 然后加入元素。
我使用linq编写了一个示例程序
string[] array1 = new string[]{"100101","100102","100101","100104","100101"};
string[] array2 = new string[] { "Testing123", "Apple123", "Dog123", "Cat123", "Animal123" };
var concatenatedString = array1.Zip(array2, (x, y) => new { First = x, Second = y }).GroupBy(t => t.First).Select(t=> string.Join(" ",t.Select(s=> s.Second))).ToList();
结果将包含连接字符串列表。
希望它有助于
答案 5 :(得分:0)
var arr1 = new [] { "100101", "100102", "100101", "100104", "100101" };
var arr2 = new [] { "Testing123", "Apple123", "Dog123", "Cat123", "Animal123" };
var result = string.Join(" ", arr2.Where((a, i) => i < arr1.Length && arr1[i] == "100101"));