如何解决如何在下一个列表附近添加添加项
我正在尝试制作一个像单词列表生成器这样的程序。 我想将第二个列表中的项目添加到第一个列表中的每个项目旁边。 `
List<string> list1 = new List<string>() {"tomato","ball","icecream","blue"};
List<string> list2 = new List<string>() { "123","yellow","green" };
`
//Values to be added to Listing 3: tomato123,tomatoyellow,tomatogreen,ball123,ballyellow,ballgreen bla bla bla
解决方法
为解决您的问题,我们将遍历其中一个列表,对于其中的每个项目,我们将使用其他列表中的单词创建所有可能的组合。使用LINQ,它看起来像这样:
var list3 = list1.Select(w1 => list2.Select(w2 => w1 + w2)).ToList();
问题在于,现在list3
的类型为List<IEnumerable<string>>
,因为我们有list1
中每个单词的组合列表。要展平结果,我们所需要做的就是将Select
投影更改为SelectMany
展平投影:
var list3 = list1.SelectMany(w1 => list2.Select(w2 => w1 + w2)).ToList();
,
根据您的要求,它可能会有用。请看看。
static void AddLists()
{
List<string> list1 = new List<string>() { "tomato","ball","icecream","blue" };
List<string> list2 = new List<string>() { "123","yellow","green" };
var resultList = from l1 in list1
from l2 in list2
select string.Concat(l1,l2);
}
,
我的建议是创建一个扩展方法,而不是创建一个难以理解的LINQ语句:读者将立即看到它的作用,它更易于测试和更改。
请参见extension methods demystified
public static IEnumerable<string> ConcatCombinations(
this.IEnumerable<string> sequenceA,IEnumerable<string> sequenceB)
{
// TODO: invent a proper name
foreach (string textA in sequenceA)
foreach (string textB in sequenceB)
yield return textA + textB;
}
此代码比使用LINQ方法的任何解决方案都更简单。任何人都将立即看到它的作用。
用法:
List<string> list1 = ...
string[] array1 = ...
List<string> concatenated = list1.ConcatCombinations(array1).ToList();
如果您想使用更通用的方法,请考虑以下问题:
public static IEnumerable<TResult> MakeCombinations<TA,TB,TResult>(
this IEnumerable<TA> itemsA,IEnumerable<TB> itemsB,Func<TA,TResult> resultSelector)
{
foreach (TA itemA in itemsA)
foreach (TB itemB in itemsB)
{
TResult result = resultSelector(itemA,itemB);
yield return result;
}
}
用法:
List<string> list1 = ...
List<string> list2 = ...
List<string> concatenated = list1.ConcatCombinations(list2,// parameter ResultSelector: concat every a and b:
(a,b) => a+b)
.ToList();
或者只是更改您的ConcatCombinations:
public static IEnumerable<string> ConcatCombinations(
this.IEnumerable<string> sequenceA,IEnumerable<string> sequenceB)
{
return sequenceA.MakeCombinations(sequenceB,(a,b) => a + b);
}
另一个完全不同的示例,向您展示代码的可重用性:
var maleBallroomDancers = ...
var femaleBallroomDancers = ...
var danceCombinations = maleBallroomDancers.MakeCombinations(femaleBallroomDancers,(male,female) => new
{
Male = male,Female = female,})
.ToList();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。