LINQ/Dictionary将两个方法连接成一个方法
本文关键字:方法 连接 一个 两个 LINQ Dictionary | 更新日期: 2023-09-27 17:50:21
我已经尝试了几乎所有的东西,我之前问过类似的问题,并得到了一些指导方针,但它不起作用,我的意思是当有两个方法时它起作用,但它伤害了所有那些重复的代码行。所以我需要帮助如何将这两个连接到一个单一的方法。
private Dictionary<string, int> SplitterMP(string[] file, bool distinct, bool pairs)
{
var query = file
.SelectMany(i => File.ReadLines(i)
.SelectMany(line => line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
.AsParallel()
.Select(word => word.ToLower())
.Where(word => !word.All(char.IsDigit)));
if (pairs)
{
var pairWise = query.Pairwise((first, second) => string.Format("{0} {1}", first, second));
return query
.Concat(pairWise)
.GroupBy(word => word)
.ToDictionary(g => g.Key, g => g.Count());
}
return query
.GroupBy(word => word)
.ToDictionary(g => g.Key, g => g.Count());
}
private Dictionary<string, int> SplitterS(string[] file, bool distinct, bool pairs)
{
List<string> allFilesWords = new List<string>();
foreach (var filename in file)
{
var query = File.ReadLines(filename)
.SelectMany(line => line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
.AsParallel()
.Select(word => word.ToLower())
.Where(word => !word.All(char.IsDigit));
if (distinct)
{
allFilesWords.AddRange(query.Distinct());
}
}
return allFilesWords
.GroupBy(word => word)
.ToDictionary(g => g.Key, g => g.Count());
}
所以第一个函数对pairs = true
和distinct = false
有效,第二个函数对pairs = false
和distinct = true
有效。我希望它在一个Splitter
方法中能够同时调用true而不是像我现在这样做一些恶作剧
我不是百分百确定你的意思,但是你能做到吗?
private Dictionary<string, int> Splitter(string[] file, bool distinct, bool pairs)
{
var query = file
.SelectMany(i => File.ReadLines(i)
.SelectMany(line => line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
.AsParallel()
.Select(word => word.ToLower())
.Where(word => !word.All(char.IsDigit)));
if (pairs)
query = query.Concat(query.Pairwise((first, second) => string.Format("{0} {1}", first, second)));
if(distinct)
query = query.Distinct();
return query
.GroupBy(word => word)
.ToDictionary(g => g.Key, g => g.Count());
}