Linq选择项目直到下一次出现
本文关键字:一次 项目 选择 Linq | 更新日期: 2023-09-27 18:22:23
我需要过滤以下列表,以返回从第一个以"Group"开头的项目开始的所有项目,直到,但不包括下一个以"Group"开头的项(或直到最后一个项目)。
List<string> text = new List<string>();
text.Add("Group Hear It:");
text.Add(" item: The Smiths");
text.Add(" item: Fernando Sor");
text.Add("Group See It:");
text.Add(" item: Longmire");
text.Add(" item: Ricky Gervais Show");
text.Add(" item: In Bruges");
过滤后,我想在第一组中有以下项目:
"Group Hear It:" " item: The Smiths" " item: Fernando Sor"
以及第二组中的以下项目:
"Group See It:" " item: Longmire" " item: Ricky Gervais Show" " item: In Bruges"
这不起作用,因为我正在筛选第一个排除"item:"项目的列表。。。我是接近TakeWhile,还是远离?
var group = text.Where(t => t.StartsWith("Group ")))
.TakeWhile(t => t.ToString().Trim().StartsWith("item"));
与Jeff Mercado的类似,但不预处理整个枚举:
public static class Extensions
{
public static IEnumerable<IList<T>> ChunkOn<T>(this IEnumerable<T> source, Func<T, bool> startChunk)
{
List<T> list = new List<T>();
foreach (var item in source)
{
if(startChunk(item) && list.Count > 0)
{
yield return list;
list = new List<T>();
}
list.Add(item);
}
if(list.Count > 0)
{
yield return list;
}
}
}
使用方式:
List<string> text = new List<string>();
text.Add("Group Hear It:");
text.Add(" item: The Smiths");
text.Add(" item: Fernando Sor");
text.Add("Group See It:");
text.Add(" item: Longmire");
text.Add(" item: Ricky Gervais Show");
text.Add(" item: In Bruges");
var chunks = text.ChunkOn(t => t.StartsWith("Group"));
您可以在生成器的帮助下非常干净地完成这项工作。生成器将跟踪当前使用的密钥,如果不引入外部变量,传统的LINQ查询就无法做到这一点。您只需要在浏览集合时决定密钥何时更改即可。一旦你得到了用于每个项目的密钥,只需按该密钥将它们分组即可。
public static class Extensions
{
public static IEnumerable<IGrouping<TKey, TResult>> ConsecutiveGroupBy<TSource, TKey, TResult>(
this IEnumerable<TSource> source,
Func<TSource, bool> takeNextKey,
Func<TSource, TKey> keySelector,
Func<TSource, TResult> resultSelector)
{
return
from kvp in AssignKeys(source, takeNextKey, keySelector)
group resultSelector(kvp.Value) by kvp.Key;
}
private static IEnumerable<KeyValuePair<TKey, TSource>> AssignKeys<TSource, TKey>(
IEnumerable<TSource> source,
Func<TSource, bool> takeNextKey,
Func<TSource, TKey> keySelector)
{
var key = default(TKey);
foreach (var item in source)
{
if (takeNextKey(item))
key = keySelector(item);
yield return new KeyValuePair<TKey, TSource>(key, item);
}
}
}
然后使用它:
var lines = new List<string>
{
"Group Hear It:",
" item: The Smiths",
" item: Fernando Sor",
"Group See It:",
" item: Longmire",
" item: Ricky Gervais Show",
" item: In Bruges",
};
var query = lines.ConsecutiveGroupBy(
line => line.StartsWith("Group"),
line => line,
line => line);
试试这个:
var i = 0;
var groups = text.GroupBy(t => t.StartsWith("Group") ? ++i : i);
我持有我们看到群条件的次数。使用i++而不是++i会让条件完成一个组,而不是启动它。
一种方法是使用类并使用LINQ从类中获得结果:
public class MediaItem {
public MediaItem(string action, string name) {
this.Action = action;
this.Name = name;
}
public string Action = string.Empty;
public string Name = string.Empty;
}
List<MediaItem> mediaItemList = new List<MediaItem>();
mediaItemList.Add(new MediaItem("Group: Hear It", "item: The Smiths"));
mediaItemList.Add(new MediaItem("Group: Hear It", "item: Fernando Sor"));
mediaItemList.Add(new MediaItem("Group: See It", "item: Longmire"));
mediaItemList.Add(new MediaItem("Group: See It", "item: Ricky Gervais Show"));
mediaItemList.Add(new MediaItem("Group: See It", "item: In Bruges"));
var results = from item in mediaItemList.AsEnumerable()
where item.Action == "Group: Hear It"
select item.Name;
foreach (string name in results) {
MessageBox.Show(name);
}
另一种方法是单独使用LINQ:
// Build the list
List<string> text = new List<string>();
text.Add("Group Hear It:");
text.Add(" item: The Smiths");
text.Add(" item: Fernando Sor");
text.Add("Group See It:");
text.Add(" item: Longmire");
text.Add(" item: Ricky Gervais Show");
text.Add(" item: In Bruges");
text.Add("Group Buy It:");
text.Add(" item: Apples");
text.Add(" item: Bananas");
text.Add(" item: Pears");
// Query the list and create a "table" to work with
var table = from t in text
select new {
Index = text.IndexOf(t),
Item = t,
Type = t.Contains("Group") ? "Group" : "Item",
GroupIndex = t.Contains("Group") ? text.IndexOf(t) : -1
};
// Get the table in reverse order to assign the correct group index to each item
var orderedTable = table.OrderBy(i => i.Index).Reverse();
// Update the table to give each item the correct group index
table = from t in table
select new {
Index = t.Index,
Item = t.Item,
Type = t.Type,
GroupIndex = t.GroupIndex < 0 ?
orderedTable.Where(
i => i.Type == "Group" &&
i.Index < t.Index
).First().Index :
t.GroupIndex
};
// Get the "Hear It" items from the list
var hearItItems = from g in table
from i in table
where i.GroupIndex == g.Index &&
g.Item == "Group Hear It:"
select i.Item;
// Get the "See It" items from the list
var seeItItems = from g in table
from i in table
where i.GroupIndex == g.Index &&
g.Item == "Group See It:"
select i.Item;
// Get the "Buy It" items I added to the list
var buyItItems = from g in table
from i in table
where i.GroupIndex == g.Index &&
g.Item == "Group Buy It:"
select i.Item;
您可能需要命令式代码来完成这项工作,我想不出LINQ解决方案。
List<List<string>> results = new List<List<string>>();
List<string> currentGroup = null;
foreach (var item in text)
{
if (item.StartsWith("Group"))
{
if (currentGroup != null) results.Add(currentGroup);
currentGroup = new List<string>();
}
currentGroup.Add(item);
}
results.Add(currentGroup);
使用干净的LINQ和lambda表达式将无法做到这一点。您可以定义一个委托方法,该方法访问位于外部范围的布尔标志(如执行该操作的实例),然后将其传递到select语句中,但我认为普通的for循环会更好。如果你这样做,你可以只记下起始和结束索引,然后提取范围,这可能是最干净的解决方案。