0

考虑三个不同的字符串列表,其中之一是列表列表。我需要搜索它们以找到一个特定的。

在这个示例中,实现了结果,但我想在一个 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;
                    }
                }
            }
        }
4

4 回答 4

1

您可以使用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"))
 {
 }
于 2013-08-10T16:26:57.990 回答
1
bool result = listOfLists.SelectMany(x => x)
                         .Concat(collectionA)
                         .Concat(collectionB)
                         .Any(x => x == "Item5");
于 2013-08-10T16:27:46.243 回答
1
var result = collectionA
    .Concat(collectionB)
    .Concat(listOfLists.SelectMany(i => i))
    .FirstOrDefault(i => i == searchString);
于 2013-08-10T16:32:38.673 回答
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;

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

于 2013-08-10T16:46:09.323 回答