如何用一个linq语句搜索多个集合



考虑三个不同的字符串列表,其中一个是列表列表。我需要全部搜索才能找到一个特定的。

在这个示例中,结果已经实现,但我想用一个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;
                    }
                }
            }
        }
bool result = listOfLists.SelectMany(x => x)
                         .Concat(collectionA)
                         .Concat(collectionB)
                         .Any(x => x == "Item5");
var result = collectionA
    .Concat(collectionB)
    .Concat(listOfLists.SelectMany(i => i))
    .FirstOrDefault(i => i == searchString);

您可以使用SelectMany来压平列表的列表,首先将collectionAcollectionA添加到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"))
 {
 }

也许这会有所帮助:

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;

您可以修改更多以获得预期结果

最新更新