LINQ query with grouping and filtering of special groups

I have a class ...

class Document
{
    public int GroupID  { get; set; }
    public bool Valid { get; set; }
    // more
}

... and a list of items: IEnumerable<Document> documents. At the first stage, which launches an object on an object through this list, these documents were checked, which means: the property Validwill be truefor some objects and falsefor other objects in the list.

Now in the second step I have to do the following:

  • If for at least one document in the group of documents (defined by all documents with the same GroupID) the flag Validis equal false, then set for all documents in the group Valid false.

For this, I have created so far the following code fragment:

var q = from d in documents
        group d by d.GroupID;
// q is now of type IEnumerable<IGrouping<int, Document>>

foreach (var dg in q) // dg = "document group", of type IGrouping<int, Document>
{
    if (dg.Any(d => !d.Valid))
    {
        foreach (var d in dg)
            d.Valid = false;
    }
}

I believe this does what I want (I have not tested it so far, though), but not very efficiently.

: , Any foreach "- " LINQ, q , ? ( , , .)

!

+5
2

, , :

var q = from d in documents
        group d by d.GroupID into g
        where g.Count() > 1 && g.Any(d => !d.Valid)
        select g;

foreach (var dg in q)
{
    foreach (var d in dg)
    {
        d.Valid = false;
    }
}

:

var q = documents.GroupBy(d => d.GroupID)
            .Where(g => g.Count() > 1 && g.Any(d => !d.Valid));
+5

Valid false, , GroupId , . :

//Find the invalid GroupIds.
var invalidIds = documents.Where(d => !d.IsValid).Select(p => p.GroupId).Distinct();

//invalidIds now holds the bad groupIds.
//So we can find out if each document GroupId is an invalid one, and if it is, mark it as invalid.
documents.Where(d => invalidIds.Contains(d.GroupId)).ToList().ForEach(p => p.IsValid = false);

, .

+1

All Articles