简体   繁体   中英

How to convert a foreach statement to LINQ using C#

I want to convert a foreach statement into LINQ in C#.

  • There is a class called Unit with three attributes A , B and C .

  • There is a List<Unit> called GetUnit .

The following code is:

  • to find the value of C if A equals to a string and
  • assign C to string ,

Is it possible to convert it to a LINQ statement?

foreach (Unit item in GetUnit)
{
    if (item.A == "This is a string")
    {
        string AAA = item.C;
    }
}

You can do:

var AAA = GetUnit.FirstOrDefault(item => item.A == "This is a string")?.C;

assuming you only expect one match, but... personally I'd just use the foreach and if .

(note: the ?.C here returns null if there is no match, or .C of the match found otherwise)

You want to find items where the property A matches This is a string and from each match, select their C property, hence:

var strings = GetUnit()
    .Where(i => i.A == "This is a string")
    .Select(i => i.C);

Extending Marc Gravell's answer, you could use the null coalescing operator like:

var AAA = GetUnit.FirstOrDefault(item => item.A == "This is a string")?.C ?? "Nothing found";

or even

var AAA = GetUnit.FirstOrDefault(item => item.A == "This is a string")?.C ?? throw new Exception("Nothing found");

Of course you should throw a more descriptive exception that fits your use case.

Apart from the given answers, you can read/follow these two resources to gain knowledge:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM