我有一个简单的值类型:

    [Serializable]
    private struct TimerInstance
    {
        public TimerInstance(string str, long nTicks)
        {
            _name = str;
            _ticks = nTicks;
        }

        private readonly string _name;
        private readonly long _ticks;

        public string Name { get { return _name; } }
        public long Ticks { get { return _ticks; } }

        public override string ToString()
        {
            return string.Format("{0,20}: {1,10:N}", Name, Ticks);
        }
    }

您会注意到它是可序列化的。然后,我列出了这些:
static private List<TimerInstance> _Timers = new List<TimerInstance>();

并使用LINQ方法从列表中消除后5%和5%的计时器:
// Return items that should be persisted.  By convention, we are eliminating the "outlier"
// values which I've defined as the top and bottom 5% of timer values.
private static IEnumerable<TimerInstance> ItemsToPersist()
{
    // Eliminate top and bottom 5% of timers from the enumeration.  Figure out how many items
    // to skip on both ends.
    int iFivePercentOfTimers = _Timers.Count / 20;
    int iNinetyPercentOfTimers = _Timers.Count - iFivePercentOfTimers * 2;

    return (from x in _Timers
            orderby x.Ticks descending
            select x).Skip(iFivePercentOfTimers).Take(iNinetyPercentOfTimers);
}

然后,我尝试将此枚举的结果序列化为XML,即仅序列化中间90%的计时器的值,而消除顶部和底部5%的值:
// Serialize the timer list as XML to a stream - for storing in an Azure Blob
public static void SerializeTimersToStream(Stream s)
{
    BinaryFormatter f = new BinaryFormatter();
    f.Serialize(s, ItemsToPersist());
}

问题是当执行此代码时,我得到以下信息:



我想我知道这是在告诉我什么-枚举数显然已生成的隐式类('System.Linq.Enumerable + d__3a`1 [[TracePerfWorker.TraceTimer + TimerInstance,TracePerfWorker')本身并未标记为可序列化的。

但这似乎是一种非常普遍的情况,我正在使用可序列化的值类型
(TimerInstance),并且仅在这些值的列表上构建LINQ查询,即枚举器仅返回TimerInstance值-然后我如何说服枚举器返回的仅仅是TimerInstance值的列表,这些列表是可序列化的?

最佳答案

在调用序列化之前,如何使用ToList获取项目列表?
您的方法将需要更改为返回List<TimerInstance>而不是IEnumerable<TimerInstance>
http://msdn.microsoft.com/en-us/library/bb342261.aspx

关于c# - LINQ IEnumerable的序列化结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3270367/

10-17 01:49