首页 > 解决方案 > 如何仅获取具有相同名称的相邻项目的列表

问题描述

我有一个看起来像这样的列表:

public static void main {
   int itemToBeSearched = 4;

   List<Item> list = new List<Item>();
        list.Add(new Item { Id = 1, Name = "name1" });
        list.Add(new Item { Id = 2, Name = "name2" });
        list.Add(new Item { Id = 3, Name = "name1" });
        list.Add(new Item { Id = 4, Name = "name1" });
        list.Add(new Item { Id = 5, Name = "name1" });
        list.Add(new Item { Id = 6, Name = "name3" });
        list.Add(new Item { Id = 7, Name = "name1" });

    //I need help in getting a return here
    var subList = GetAdjacentList(list, itemToBeSearched);
}

public List<Item> GetAdjacentList(List list, int itemToBeSearched)
{
    //Need help with the logic or linq here that would give a return such as
    return List<Item> list = new List<Item>();
        list.Add(new Item { Id = 3, Name = "name1" });
        list.Add(new Item { Id = 4, Name = "name1" });
        list.Add(new Item { Id = 5, Name = "name1" });
}

并且期望的输出应该是:一个仅包含Item2, Item3and的子列表Item4

我只想要返回一个只包含Item3, Item4和的子列表,Item5因为它们彼此相邻且具有相同的名称,即name1.

Item1并且Item7不包括在内,即使它们的名称为 asname1因为它不靠近相邻的组。

有人可以使用 Linq 或其他方式帮助我解决这个问题吗?

标签: c#linq

解决方案


可能有一种更简单的方法,但我想出了这个。它不使用任何 LINQ,但它确实维护了列表项的顺序(假设这很重要)。

public static List<Item> GetAdjacentList(List<Item> list, int itemToBeSearched)
{
    List<Item> result = new List<Item>();
    // find the index of the item we're searching for
    int itemIdx = list.FindIndex(i => i.Id == itemToBeSearched);
    if (itemIdx == -1)
    {
        return result; // not found, return empty list
    }

    // store the item for comparisons
    Item item = list[itemIdx];

    // loop backwards starting from the current item ann going to the 0th element
    for (int i = itemIdx; i >= 0; --i)
    {
        // if this item is the search item, or the name matches, add it to the list
        if (i == itemIdx || list[i].Name == item.Name)
        {
            result.Add(list[i]);
        }
        else
        {
            // exit the loop as we've run out of items with the same name
            break;
        }
    }

    if (result.Count > 0)
    {
        result.Reverse(); // we've added items in reverse order, so reverse the list
    }

    // loop through all the items from the next item to the end of the list
    for (int i = itemIdx + 1; i < list.Count; ++i)
    {
        // if the name matches add it to the result list
        if (list[i].Name == item.Name)
        {
            result.Add(list[i]);
        }
        else
        {
            // we've reached the end of matching names so break
            break;
        }
    }
    // return the result
    return result;
}

推荐阅读