c# - 如何仅获取具有相同名称的相邻项目的列表
问题描述
我有一个看起来像这样的列表:
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, Item3
and的子列表Item4
。
我只想要返回一个只包含Item3, Item4
和的子列表,Item5
因为它们彼此相邻且具有相同的名称,即name1
.
Item1
并且Item7
不包括在内,即使它们的名称为 asname1
因为它不靠近相邻的组。
有人可以使用 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;
}
推荐阅读
- linux - 将博客从子域重定向到域的文件夹,不同的托管
- linux - Postgres pg_dump 转储文件大小大于 pg_database_size
- html - SVG 框尺寸大于应有的尺寸
- r - 在 R 中找不到函数“left_join”
- sql-server - 我可以将 Flyway 与 SQL Server 加密一起使用吗?
- java - 查找数组中的最小整数,然后将其与第一个单元格交换
- postgresql - 错误:类型“日期”不允许使用类型修饰符(PostgreSQL)
- elasticsearch - Elastic Search (5.0) 过滤上下文术语查询不起作用
- c# - 库 youtubeExtractor 给我一个错误
- java - findByAll(), findBy{columnName} 在 Spring 数据 jpa 中不起作用