gpt4 book ai didi

c# - LINQ(或)在循环中使用处理?选择什么?

转载 作者:太空宇宙 更新时间:2023-11-03 14:08:39 27 4
gpt4 key购买 nike

我遇到了以下情况,需要决定采用哪种方法 CalculateEntrySummaryInArray()(或)CalculateEntrySummaryInLINQ() 就

而言是最好的
  • 更好的代码
  • 代码可维护性
  • 能够理解代码
  • 性能(“事件列表”最多包含 100,000事件)

请提出建议。

 public enum EntryType
{
None,
Entry,
Exit
}
public class EventEntity
{
public EventEntity()
{
Time = new DateTime(0);
Name = string.Empty;
Type = EntryType.None;
}

public DateTime Time { get; set; }
public string Name { get; set; }
public EntryType Type { get; set; }
}
public class EntrySummary
{
public EntrySummary()
{
Time = new DateTime(0);
Name = string.Empty;
Count = 0;
}

public DateTime Time { get; set; }
public string Name { get; set; }
public int Count { get; set; }
}

public void CalculateEntrySummaryInArray(List<EventEntity> events)
{
List<EntrySummary> summary = new List<EntrySummary>();

foreach (var entryEvent in events)
{
if (entryEvent.Type != EntryType.Entry) continue;

if (summary.Count == 0)
{
EntrySummary entrySummary = new EntrySummary();
entrySummary.Count = 1;
entrySummary.Name = entryEvent.Name;
entrySummary.Time = entryEvent.Time;

summary.Add(entrySummary);
}
else
{
bool isAddedToSummary = false;

foreach (var item in summary)
{
if (item.Name == entryEvent.Name && item.Time.Date == entryEvent.Time.Date)
{
item.Count++;
isAddedToSummary = true; break;
}
}

if (isAddedToSummary == false)
{
EntrySummary entrySummary = new EntrySummary();
entrySummary.Count = 1;
entrySummary.Name = entryEvent.Name;
entrySummary.Time = entryEvent.Time;

summary.Add(entrySummary);
}
}
}

foreach (var item in summary)
{
MessageBox.Show(item.Time.Date.ToString() + " " + item.Name + " " + item.Count);
}
}

public void CalculateEntrySummaryInLINQ(List<EventEntity> events)
{
var summary = from entryEvent in events
where entryEvent.Type == EntryType.Entry
group entryEvent by new { entryEvent.Time.Date, entryEvent.Name} into groupedEvent
select new { groupedEvent.Key.Date, groupedEvent.Key.Name, Count = groupedEvent.Count() };

foreach (var item in summary)
{
MessageBox.Show(item.Date.ToString() + " " + item.Name + " " + item.Count);
}
}

最佳答案

这是一个意见问题,很可能会结束,但我个人会采用第三种方法:

foreach (var item in events
.Where(e => e.Type = EntryType.Entry)
.GroupBy(e => new { e.Time.Date, e.Name }) // I think, kinda forget
.Select(ge => new { ge.Key.Date, ge.Key.Name, Count = ge.Count() }))
{
MessageBox.Show(...);
}

我不是“select”linq 语法的忠实拥护者,因为我觉得您在其中塞入了一种完全不同的语言,但我并不太自豪能够利用它的工作原理。本质上,我的代码在没有语法糖精的情况下做同样的事情。

关于c# - LINQ(或)在循环中使用处理?选择什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8530641/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com