title: System.Guid.NewGuid() in linq select
body: <p>I wanted to generate a unique identifier for the results of a Linq query i did on some date.
  Initially i thought of using Guid for that but stumbling upon this problem i had to improvise.
  However I'd like to see if anyone could have a solution using Guid so here we go.</p>
  
  <p>Imagine we have:</p>
  
  <pre><code>class Query
  {
      public class Entry
      {
          public string Id { get; set; }
          public int Value { get; set; }
      }
  
      public static IEnumerable&lt;Entry&gt; GetEntries( IEnumerable&lt;int&gt; list)
      {
          var result = 
              from i in list
              select new Entry
              {
                  Id = System.Guid.NewGuid().ToString("N"),
                  Value = i
              };
          return result;
      }
  }
  </code></pre>
  
  <p>Now we want Id to be unique for each entry, but we need this value to be the same for each traversal of the IEnumerable we get from GetEntries. This means that we want calling the following code:</p>
  
  <pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 2, 3, 4, 5 };
  IEnumerable&lt;Query.Entry&gt; entries = Query.GetEntries(list);
  Console.WriteLine("first pass");
  foreach (var e in entries) { Console.WriteLine("{0} {1}", e.Value, e.Id); }
  Console.WriteLine("second pass");
  foreach (var e in entries) { Console.WriteLine("{0} {1}", e.Value, e.Id); }
  </code></pre>
  
  <p>to give us something like:</p>
  
  <p>first pass</p>
  
  <pre>
  1 47f4a21a037c4ac98a336903ca9df15b
  2 f339409bde22487e921e9063e016b717
  3 8f41e0da06d84a58a61226a05e12e519
  4 013cddf287da46cc919bab224eae9ee0
  5 6df157da4e404b3a8309a55de8a95740
  </pre>
  
  <p>second pass</p>
  
  <pre>
  1 47f4a21a037c4ac98a336903ca9df15b
  2 f339409bde22487e921e9063e016b717
  3 8f41e0da06d84a58a61226a05e12e519
  4 013cddf287da46cc919bab224eae9ee0
  5 6df157da4e404b3a8309a55de8a95740
  </pre>
  
  <p>However we get:</p>
  
  <p>first pass</p>
  
  <pre>
  1 47f4a21a037c4ac98a336903ca9df15b
  2 f339409bde22487e921e9063e016b717
  3 8f41e0da06d84a58a61226a05e12e519
  4 013cddf287da46cc919bab224eae9ee0
  5 6df157da4e404b3a8309a55de8a95740
  </pre>
  
  <p>second pass</p>
  
  <pre>
  1 a9433568e75f4f209c688962ee4da577
  2 2d643f4b58b946ba9d02b7ba81064274
  3 2ffbcca569fb450b9a8a38872a9fce5f
  4 04000e5dfad340c1887ede0119faa16b
  5 73a11e06e087408fbe1909f509f08d03
  </pre>
  
  <p>Now taking a second look at my code above I realized where my error was: 
  The assignment of Id to Guid.NewGuid().ToString("N") gets called every time we traverse the collection and thus is different everytime.</p>
  
  <p>So what should i do then?
  Is there a way i can reassure that i will get with only one copy of the collection everytime?
  Is there a way that i'm sure that i won't be getting the new instances of the result of the query?</p>
  
  <p>Thank you for your time in advance :)</p>