简体   繁体   中英

Linq: Selecting a new List<Guid> in C#

Using linq I am trying to get a List[Guid] , but I am not able to.

I tried this:

var myGuidList = from x in
                 mydatasource
                 where x.Field==value
                 select new Guid(){x.TheGuid};   <- Problem here

It's not clear what the type of TheGuid property is but if it is a string you could use the following:

IEnumerable<Guid> myGuidList = 
    from x in mydatasource
    where x.Field == value
    select new Guid(x.TheGuid);

And if it is a Guid, well, you could select it directly:

IEnumerable<Guid> myGuidList = 
    from x in mydatasource
    where x.Field == value
    select x.TheGuid;

and if you want to get a List<Guid> , simply use the .ToList() extension method on the result:

List<Guid> guids = myGuidList.ToList();

Why do you need to create a new instance of a Guid if you already have one?

var myGuids = from x in
              mydatasource
              where x.Field == value
              select x.TheGuid;

(assuming that x.TheGuid is a Guid of course)

If you want a List<Guid> :

List<Guid> myGuidList = myGuids.ToList();

Note that Guid ha no conctructor that takes a Guid (makes little sense anyway) or a parameterless constructor and it also has no property(just a field Empty ), that's why your code cannot compile.

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