Selecting an item from IEnumerable

Possible duplicate:
Query results cannot be listed more than once?

I use an entity structure to select and return a group of objects from my database using a stored procedure.

var results = dataContext.loadData(testargument);

I want to count this returned set (to make sure that only 1 record is returned, then take the first item in this list.

if(results.Count() == 1)
{
    ReturnedEntity entity = results.First();
}

However, when I make this call, I get the error message "The query result could not be listed more than once." Does anyone know how I can do this correctly? I assume that calling the Count () method changes the data, and I'm not sure whether to return it to the list before calling the first () method. I tried results.ToList (). First (), but getting the same error.

, , First() , , , 1 .

+3
6

, ToList(). , , , . FirstOrDefault().

var results = dataContext.loadData(testargument).ToList();

ReturnedEntity entity = results.FirstOrDefault();

if(results.Length == 1)
    ReturnedEntity entity = results.First();
+3

ReturnedEntity entity = results.First();

if (entity!= null)

0

.ToList() , , .

var resultList = results.ToList();
if(resultList.Count == 1)
{
    ReturnedEntity entity = resultList.First();
}
0
var resultList = results.ToList();
if(resultList.Count == 1)
{
    ReturnedEntity entity = resultList.First();
}
0

IEnumerable . . IEnumerable , , , .

If you want to know the number of elements without iterating over them, you can use it IList<T>, it has the Count property.

0
source

I think that

try
{
    var result = dataContext.loadData(testargument).Single()
}
catch (InvalidOperationException)
{
    // Oops not a single result
}

- a better approach if obtaining more or less than one result is exceptional. If during normal execution more or less than one result occurs, you can do

var result = dataContext.loadData(testargument).SingleOrDefault()

if (result != null)
{
    // Continue as usual
}
else
{
   // Oops, not a single result
}

If you will reuse a set that you could use the extension ToList,

var results = dataContext.loadData(testargument).ToList(); 

if(results.Count == 1) 
{     
    ReturnedEntity entity = results[0];
}
else
{
    // Oops, not a single result
}

IListsupports multiple enumerations, has a property Countand an index accessor, IEnumerable- no.

-1
source

All Articles