考虑三个不同的字符串列表,其中一个是列表列表。我需要搜索它们以找到特定的一个。
在此示例中,结果已实现,但我想在一个Linq语句中执行此操作。请注意,我不想更改现有集合,也不想创建任何新集合。
var collectionA = new List<string>() {"Item1", "Item2"};
var collectionB = new List<string>() { "Item3", "Item4" };
var listOfLists = new List<List<string>>() {new List<string>() {"Item5", "Item6"}, new List<string>(){ "Item7", "Item8"}};
//Is there a better Linq way to do this?
var searchString = "Item5";
var item = collectionA.FirstOrDefault(i => i == searchString);
if (item == null)
{
item = collectionB.FirstOrDefault(i => i == searchString);
if (item == null)
{
foreach (var listOfList in listOfLists)
{
item = listOfList.FirstOrDefault(i => i == searchString);
if (item != null)
{
break;
}
}
}
}
答案 0 :(得分:1)
您可以使用SelectMany
展平列表,首先将collectionA
和collectionA
添加到listOfLists
:
listOfLists.AddRange(new[] {collectionA, collectionB});
if (listOfLists.SelectMany(x => x).Any(y => y == "Item5"))
{
}
对于您不想更改现有馆藏的新编辑,也不创建新馆藏,您可以这样做:
if (listOfLists.Any(x => x.Any(y => y == "Item5"))
|| collectionA.Any(x => x == "Item5")
|| collectionB.Any(x => x == "Item5"))
{
}
答案 1 :(得分:1)
bool result = listOfLists.SelectMany(x => x)
.Concat(collectionA)
.Concat(collectionB)
.Any(x => x == "Item5");
答案 2 :(得分:1)
var result = collectionA
.Concat(collectionB)
.Concat(listOfLists.SelectMany(i => i))
.FirstOrDefault(i => i == searchString);
答案 3 :(得分:0)
也许这会有所帮助:
var collectionA = new List<string>() { "Item1", "Item2" };
var collectionB = new List<string>() { "Item3", "Item4" };
var listOfLists = new List<List<string>>() { new List<string>() { "Item5", "Item6" }, new List<string>() { "Item7", "Item8" } };
var val = from y in (from x in listOfLists[0] select x) where y == "Item5" select y;
您可以修改更多内容以获得预期结果