Replacing foreach with LINQ query

I have the following code in one of my methods:

foreach (var s in vars)
{
    foreach (var type in statusList)
    {
        if (type.Id == s)
        {
            Add(new NameValuePair(type.Id, type.Text));
            break;
        }
    }
}

This seems ineffective to me, and I was wondering if there is a way to replace at least one of the ancestors with the LINQ query. Any suggestions?

EDIT: vars is an array of strings, and the Add method adds an element to the CSLA NameValueList.

+3
source share
6 answers

EDIT: I haven't noticed break;until

If there can be more than one type with the corresponding identifier, then you need to use FirstOrDefaultin accordance with Keith's answer or my second code example below.

EDIT: "multi-from", , /hashcode type.Id.

, , :

var query = from s in vars
            join type in statusList on s equals type.Id
            select new NameValuePair(type.Id, type.Text);

foreach (var pair in query)
{
    Add(pair);
}

, AddRange, IEnumerable<NameValuePair>, AddRange(query).

LookUp. "s".

var lookup = types.ToLookup(type => type.Id);
foreach (var s in vars)
{
    var types = lookup[s];
    if (types != null)
    {
        var type = types.First(); // Guaranteed to be at least one entry
        Add(new NameValuePair(type.Id, type.Text));
    }
}

, , .

+6

:

var types =
    from s in vars
    let type = (
        from tp in statusList
        where tp.Id == s ).FirstOrDefault()
    where type != null
    select new NameValuePair(type.Id, type.Text)
+12

- :

foreach(var s in vars) {
    var type = statusList.FirstOrDefault(t => t.Id == s);
    if (type != null)
        Add(new NameValuePair(type.Id, type.Text));
}

, vars ForEach, ( overLINQify):

vars.ForEach(s => {
    var type = statusList.FirstOrDefault(t => t.Id == s);
    if (type != null)
       Add(new NameValuePair(type.Id, type.Text));
});

, type - .

+2

Add , :

IEnumarable<NamedValuePair> result = statusList.Where(type => type.Id == s).Select(new NameValuePair(type => type.Id, type.Text));
+2

Bart de Smet ForEach IEnumerable.

+1
source

I do not see the answer with a group connection, so here is one:

var result = vars
  .GroupJoin
  (
    statusList,
    s => s,
    type => type.Id,
    (s, g) => g.Any() ? g.First() : null
  )
  .Where(type => type != null)
  .Select(type => new NameValuePair(type.Id, type.Text));
+1
source

Source: https://habr.com/ru/post/1703881/


All Articles