LINQ:如何申报的IEnumerable [AnonymousType]?LINQ、IEnumerable、AnonymousType

2023-09-03 10:44:20 作者:一介草民.

这是我的功能:

    private IEnumerable<string> SeachItem(int[] ItemIds)
    {
        using (var reader = File.OpenText(Application.StartupPath + @"\temp\A_A.tmp"))
        {
            var myLine = from line in ReadLines(reader)
                         where line.Length > 1
                         let id = int.Parse(line.Split('\t')[1])
                         where ItemIds.Contains(id)
                         let m = Regex.Match(line, @"^\d+\t(\d+)\t.+?\t(item\\[^\t]+\.ddj)")
                         where m.Success == true
                         select new { Text = line, ItemId = id, Path = m.Groups[2].Value };
            return myLine;
        }
    }

我得到一个编译错误,因为MYLINE不是IEnumerable的[字符串]我不知道该怎么写了IEnumerable [匿名]

I get a compile error,because "myLine" is not a IEnumerable[string] and I don't know how to write IEnumerable[Anonymous]

无法隐式转换类型'System.Collections.Generic.IEnumerable [AnonymousType#1到System.Collections.Generic.IEnumerable [字符串]

"Cannot implicitly convert type 'System.Collections.Generic.IEnumerable[AnonymousType#1]' to 'System.Collections.Generic.IEnumerable[string]'"

推荐答案

您不能声明的IEnumerable&LT; AnonymousType&GT; ,因为该类型具有在构建时没有(已知)的名称。所以,如果你想使用这种类型的函数声明,使它成为一个正常的类型。或者只是修改您的查询返回一个的IEnumerable&LT;字符串&GT; 并坚持该类型

You cannot declare IEnumerable<AnonymousType> because the type has no (known) name at build time. So if you want to use this type in a function declaration, make it a normal type. Or just modify your query to return a IENumerable<String> and stick with that type.

还是回到的IEnumerable&LT; KeyValuePair&LT;的Int32,字符串&GT;&GT; 使用下面的SELECT语句

Or return IEnumerable<KeyValuePair<Int32, String>> using the following select statement.

select new KeyValuePair<Int32, String>(id, m.Groups[2].Value)