Title: Using Linq to object, how can I get one field's value based on another in the same list
Tags: c#;linq;linq-to-objects
Question: I have a class that is defined as following:

```public class MyClass
{
    public int ID { get; set; }
    public string Name { get; set; }
}
```

Then I have a logic where I build a list of that class:

```MyList = new List<MyClass&gt;;
foreach(MyClassData myClass in Service.MyClassList)
{
    MyList.Add(new MyClass{ID = myClass.ID, Name = myClass.Name});
}
```

Now, I need to get an 'ID' based on the 'Name'.

I'm trying the following:

```int id01 = MyList.Where(x =&gt; x.FileName.Equals("File01")).Single(x =&gt; x.FileID)
```

Doing that I'm getting an error message:

```
  Cannot implicitly convert type 'int' to 'bool'
```

How would I do that using LINQ?

Comment: int id01 = MyList.Where(x => x.FileName.Equals("File01")).Select(x => x.ID).FirstOrDefault();  Do not know where you are getting FileID (should be just ID)

Here is the accepted answer: The ```Single``` method's is:

```
```public static TSource Single<TSource&gt;(
  this IEnumerable<TSource&gt; source,
  Func<TSource, bool&gt; predicate
)
```
```

It gets a predicate that should return a boolean but you are returning an integer. It is used for filtering and not projecting.

What you are looking for is:

```int id01 = MyList.Single(x =&gt; x.FileName.Equals("File01")).FileID;
```

Or better use ```SingleOrDefault```:

```int id01 = MyList.SingleOrDefault(x =&gt; x.FileName.Equals("File01"))?.FileID;
```

Also see if you want the ```SingleOrDefault``` or the ```FirstOrDefault```



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:11/07/17', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c#><linq><linq-to-objects>', 'Title': "Using Linq to object, how can I get one field's value based on another in the same list", 'ViewCount': 1203, 'id': 47165953, 'user_AboutMe': '<p>Working with .NET for the past 5 years.\nWorked with VB and JAVA.</p>\n\n<p>After work releasing stress by working out.\nLove outdoor activities like fishing, camping and hiking</p>\n', 'user_AccountId': 4999564.0, 'user_DisplayName': 'gene', 'user_Reputation': 2006.0, 'user_Views': 395.0, 'user_id': 4019002.0}}