对字符串列表设置操作
本文关键字:操作 设置 列表 字符串 | 更新日期: 2023-09-27 18:35:43
我得到了一个字符串列表,我想在上面做一个操作,将每个项目与其余项目连接起来。下面的测试目前失败,我认为连接不是我应该使用的正确linq方法 - 你能告诉我如何完成这项工作吗?输出的模式应该告诉投影应该如何,如果不是,规则很简单:取一个项目并与所有其他项目连接,然后移动到下一个项目。测试如下:
[Test]
public void Should_concatenate_all_items()
{
var items = new List<string> {"a", "b", "c", "d"};
var concatenatedList = items .Join(items , x => x, y => y, (x, y) => string.Concat(x, y));
foreach (var item in concatenatedList)
{
//Should output:ab
//Should output:ac
//Should output:ad
//Should output:bc
//Should output:bd
//Should output:cd
Console.WriteLine(item);
}
}
注意:我使用的是 .NET 3.5。
你可以使用这样的东西:
var concatenatedList =
from x in items.Select((str, idx) => new { str, idx })
from y in items.Skip(x.idx + 1)
select x.str + y;
或者用流畅的语法:
var concatenatedList =
items.Select((str, idx) => new { str, idx })
.SelectMany(x => items.Skip(x.idx + 1), (x, y) => x.str + y);
我认为我的解决方案可能矫枉过正,但在现实世界中它可能更有帮助。另外,我在 Linq 中找不到一种干净的方法来做到这一点。Linq's Except 似乎不适合这个。
可以使用 IEnumerator 为您枚举值。
public class ConcatEnum : IEnumerator
{
public List<String> _values;
// Enumerators are positioned before the first element
// until the first MoveNext() call.
int position1 = 0;
int position2 = 0;
public ConcatEnum(List<String> list)
{
_values = list;
}
public bool MoveNext()
{
position2 = Math.Max(position2 + 1, position1 + 1);
if (position2 > _values.Count - 1){
position1++;
position2 = position1 + 1;
}
return position1 < _values.Count - 1;
}
public void Reset()
{
position1 = 0;
position2 = 0;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public String Current
{
get
{
try
{
return _values[position1] + _values[position2];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
public IEnumerator GetEnumerator()
{
this.Reset();
while (this.MoveNext())
{
yield return Current;
}
}
}
这样称呼它:
var items = new List<string> { "a", "b", "c", "d" };
foreach (var i in new ConcatEnum(items))
{
//use values here
}
var concatenatedList = (from i in items
from x in items
where i != x
select string.Concat(i, x)).ToList();
对于您列出的确切输出:
var concatenatedList = (from i in items
from x in items
where i != x && items.IndexOf(i) < items.IndexOf(x)
select string.Concat(i, x)).ToList();