9

我需要过滤以下列表以返回以“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"

这不起作用,因为我在第一个排除“项目:”项目的位置过滤列表......我是关闭TakeWhile还是远离?

var group = text.Where(t => t.StartsWith("Group ")))
   .TakeWhile(t => t.ToString().Trim().StartsWith("item"));
4

6 回答 6

12

像 Jeff Mercado's 但不预处理整个可枚举:

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"));
于 2013-07-16T01:26:18.240 回答
2

您可以在生成器的帮助下相当干净地完成此操作。生成器将跟踪当前正在使用的密钥,这是在不引入外部变量的情况下使用传统 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);
于 2013-07-16T01:06:26.023 回答
1

一种方法是使用类并使用 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;
于 2013-07-16T00:25:26.283 回答
1

试试这个:

var i = 0;
var groups = text.GroupBy(t => t.StartsWith("Group") ? ++i : i);

i 持有我们看到组条件的次数。使用 i++ 而不是 ++i 会让条件完成一个组而不是启动它。

于 2013-07-16T01:02:01.047 回答
0

您可能需要命令式代码来执行此操作,我想不出 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);
于 2013-07-16T00:18:00.723 回答
0

您将无法使用干净的 LINQ 和 lambda 表达式来做到这一点。您可以定义一个委托方法来访问外部范围内的布尔标志(例如在执行 this 的实例上),然后将其传递给 select 语句,但我认为普通的 for 循环会更好。如果你这样做,你可以只记下开始和结束索引然后提取范围,这可能是最干净的解决方案。

于 2013-07-16T00:27:29.600 回答